c++ - 无法从派生指针访问公共(public)基成员

标签 c++ inheritance polymorphism

为什么这段代码不能编译? (海合会 4.7.0)

// Class with a simple getter/setter pair.
class Base {
public:
    Base () : m_Value(0) {  }

    virtual ~Base () {  }

    // Getter
    virtual int value () { return m_Value; }

    // Setter
    virtual void value (int Val) { m_Value = Val; }

private:
    int m_Value;
};

// Derived class overrides the setter.
class Derived : public Base {
public:
    void value (int Val) {
            // do some stuff here...
    }
};

int main()
{
    Derived * instance = new Derived();
    int x = instance->value();  // ERROR
    return 0;
}

构建日志:

test.cpp: In function 'int main()':
test.cpp:29:25: error: no matching function for call to 'Derived::value()'
test.cpp:29:25: note: candidate is:
test.cpp:21:7: note: virtual void Derived::value(int)
test.cpp:21:7: note:   candidate expects 1 argument, 0 provided

为什么编译器在使用 Derived* 时无法从 Base 中看到“int value()”?

改变

Derived * instance = new Derived();

Base * instance = new Derived();

有效(但在我的案例中我需要派生指针)。

同时重命名基本的 getter/setter 函数以表示 getValue() 和 setValue(int) 有效。我可以为我的代码使用各种解决方法,但我只是好奇为什么这段代码无法编译。

最佳答案

语言是这样工作的:当一个子类覆盖一个名称的成员时,它会隐藏父类中所有未覆盖的名称。这是为了防止意外组合应作为集合重写的基方法和父方法。

您可以将 using Base::value; 放在您的子类中以引入父类方法。

关于c++ - 无法从派生指针访问公共(public)基成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837701/

相关文章:

c++ - 如何将 std::regex_search 与超过 497 个字符的 wstring 一起使用?

c++ - 谷歌 C++ 风格指南。为什么输入然后输出参数排序?

c++ - 将套接字绑定(bind)到特定网络

C++ - 指向类的指针数组

c# - 如何使用泛型类型的子类初始化泛型属性?

java - 使多态性打败那些 switch/case 语句的麻烦

python - 在子类python中调用基类方法

c++ - 运行时类型信息(为什么这段代码不起作用)

inheritance - 开闭原则与继承的区别

java - 使用多态性从 JSON 生成对象