为什么此代码不能编译? (GCC 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
为什么编译器看不到 'int值()' 时使用派生*?
更改
Derived * instance = new Derived();
到
Base * instance = new Derived();
作品(但我需要在我的情况下得到的指针)。
也重命名基地getter/setter函数说getValue()和setValue(int)的作品。我可以为我的代码使用各种解决方法,但我只是很好奇为什么此代码无法编译。
的可能重复[为什么在基类的派生类隐藏其他重载的重载函数?( http://stackoverflow.com/questions/1628768/why-does-an-overridden-function-in-the-derived-class-hide-other-overloads-of-the) – Mat