Qua*_*key 4 c++ polymorphism inheritance
为什么这段代码不能编译?(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;
}
Run Code Online (Sandbox Code Playgroud)
构建日志:
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
Run Code Online (Sandbox Code Playgroud)
为什么编译器在使用Derived*时无法从Base看到'int value()'?
更改
Derived * instance = new Derived();
Run Code Online (Sandbox Code Playgroud)
至
Base * instance = new Derived();
Run Code Online (Sandbox Code Playgroud)
工作(但我需要在我的情况下派生指针).
还要将基本getter/setter函数重命名为getValue()和setValue(int).我可以为我的代码使用各种变通方法,但我只是好奇为什么这个代码无法编译.
Mar*_*k B 11
这就是语言的工作方式:当子类重写名称的成员时,它会隐藏父语句中所有未重写的名称.这是为了防止意外组合应该作为集重写的基本方法和父方法.
您可以放入using Base::value;子类以引入父方法.
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |