【发布时间】:2014-01-07 22:29:59
【问题描述】:
我正在尝试学习 C++ 中的继承。我写了一些代码来学习虚函数。
#include <iostream>
using namespace std;
class A {
int a;
public:
A() {}
virtual int get_count() const = 0;
int get_A() { return a; }
};
class B : public A{
public:
int b;
B() {}
B(A& base)
: b(base.get_count()) {}
virtual int get_count() const { return 10; }
};
void func(A& base) {
B derived(base);
cout << derived.b;
}
int main() {
A base;
B derived;
func(derived);
}
当我尝试编译时出现此错误:
test_inheritance_vir.cpp: In function ‘int main()’:
test_inheritance_vir.cpp:32: error: cannot declare variable ‘base’ to be of abstract type ‘A’
test_inheritance_vir.cpp:5: note: because the following virtual functions are pure within ‘A’:
test_inheritance_vir.cpp:10: note: virtual int A::get_count() const
你能告诉我我做错了什么吗?
【问题讨论】:
标签: c++ inheritance virtual