为什么这段代码不能编译? (海合会 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/