简体   繁体   English

与子构造函数同名的继承类成员

[英]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.

相关问题 对 class 成员和构造函数参数使用相同的名称 - Use same name for class member and constructor parameter C ++继承类具有同名成员 - C++ inherited class has member of same name 在派生类构造函数中复制继承的成员是否有效? - Is it valid to copy an inherited member in the derived class constructor? 继承的构造函数无法初始化抽象类的继承成员 - Inherited member from an abstract class can't be initialized by the inherited constructor 在构造函数中使用类成员名称 - Using class member name in a constructor 父类和子类中的c ++同名成员 - c++ same name member in parent and child class 具有相同名称的成员隐藏的变量(从基类模板继承)的偏移量 - Offset of a variable (inherited from the base template class) shadowed by a member with the same name 为什么继承的函数会更改基类中的成员变量,而不是与之名称相同的对象之一 - why inherited functions changes the member variables in base class not the one of the same name of object called it 派生类构造函数初始化列表中的多重继承和继承的数据成员 - Multiple Inheritance and inherited data member in the derived class constructor initialisation list C ++ 14在类构造函数初始化列表中初始化继承的成员 - C++14 Initializing inherited member in class constructor initialization list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM