【发布时间】:2013-07-02 14:34:50
【问题描述】:
包含纯虚函数的类不能有对象。这就是我对纯虚函数的想法。我有以下程序,它编译没有任何错误。
#include<iostream>
using namespace std;
class Father {
public:
virtual void foo()=0;
};
class Son:public Father {
// Nothing here
};
int main() {
}
这是意料之中的,因为这两个类都没有对象。但是,当我尝试对包含纯虚函数的类进行多级继承时,以下程序给了我错误。
#include<iostream>
using namespace std;
class Father {
public:
virtual void foo()=0;
};
class Son:public Father {
// Nothing here
};
class Grand_Son:public Son {
void foo() {
cout<<"\nFunction foo From Grand_Son\n";
}
};
int main() {
Grand_Son x;
x.foo();
}
错误如下所示。
In function 'int main()':|
|error: 'virtual void Grand_Son::foo()' is private|
|error: within this context|
||=== Build finished: 2 errors, 0 warnings ===|
错误是出乎意料的,因为我将 Son 和 Grand_Son 类继承为 public。
是否可以对涉及纯虚函数的类进行多级继承?
有什么建议吗?谢谢。
【问题讨论】:
-
如果某些东西被认为是私有的,请检查它是否真的在你班级的公共部分。它在您的基类中是公开的,但在
Grand_Son中不公开。 -
有趣的是,当使用
Father* x = new Grand_Son; x->foo();时,它会没事的,因为现在,foo() 是通过Father 访问的,它是公共的。这可用于强制 foo 仅通过多态性使用。
标签: c++