【发布时间】:2019-08-05 07:02:17
【问题描述】:
考虑这个例子:
class Label{
public:
std::string Text;
};
class Text:
public Label
{
public:
Text(std::string text) {}
};
int main()
{
Text text("");
text.Text; //<---- GCC CE: Invalid use of 'class Text'
return 0;
}
class Text:
public Label
{
public:
Text(std::string text) {}
using Label::Text; // doesn't help either
};
如果继承的类成员与子类同名,如何访问它?
class Text:
public Label
{
public:
Text(std::string text):
Text::Text(Label::Text){}
std::string &Text;
};
这样的东西可以吗? (我知道上面的代码没有。)
【问题讨论】:
-
没有nice 访问变量的方法。一种可能的解决方法是对此类变量使用“getters”和“setters”。
-
顺便说一句:你有没有注意到
Text这个名字在那个代码示例中被过度使用了?如果您为正在处理的事情选择不同的名称,而不是解决您遇到的问题,也许它会有助于清晰。 -
我正在实现包装器并尝试模仿现有元素的架构设计,当然名称相同。因此,如果在现有术语中,“Text”类型的元素是“Label”的子元素,并且“Label”中有“Text”属性 - 我无能为力。
标签: c++ inheritance gcc compiler-errors class-members