[英]Inherited class member with the same name as child constructor
Consider this example: 考虑这个例子:
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
};
How could one access inherited class member if it has the same name as child class? 如果它与子类具有相同的名称,那么如何访问继承的类成员?
class Text:
public Label
{
public:
Text(std::string text):
Text::Text(Label::Text){}
std::string &Text;
};
Could something like this work? 这样的事可以吗? (I know that code above does not.)
(我知道上面的代码没有。)
Here's a workaroud (which is quit confusing); 这是一个workaroud(这是令人困惑的); you can access data member of base class via the base class name.
您可以通过基类名称访问基类的数据成员。 eg
例如
text.Label::Text;
Despite the fact that the right answer is (posted by @songyuanyao) 尽管正确答案是(由@songyuanyao发布)
text.Label::Text;
I have figured out how to avoid this kinda odd syntax. 我已经想出如何避免这种奇怪的语法。
Simple "hack" with old C-style typedef will do the trick: 使用旧的C风格typedef进行简单的“hack”就可以了:
typedef class Text_:
public Label
{
public:
Text_(std::string text){}
}Text;
And now suddenly code example compiles. 现在突然代码示例编译。 Woah ... C++ magic ...
哇 ...... C ++魔术 ......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.