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

Inherited class member with the same name as child constructor

本文关键字:继承 成员 构造函数      更新时间:2023-10-16

考虑这个例子:

    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;
    };

这样的事情能行得通吗?(我知道上面的代码没有。

这是一个工作障碍(这很令人困惑(; 您可以通过基类名称访问基类的数据成员。

例如
text.Label::Text;

尽管正确的答案是(由@songyuanyao发布(

text.Label::Text;

我已经想出了如何避免这种奇怪的语法。

使用旧的 C 样式 typedef 进行简单的"黑客"就可以了:

    typedef class Text_:
        public Label
    {
    public:
        Text_(std::string text){}
    }Text;

现在突然代码示例编译。......C++魔法...