爲什麼此代碼不能編譯? (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