我正在尝试学习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你能告诉我我哪里做错了吗?
发布于 2014-01-08 06:32:39
您正在尝试使用A base;实例化一个类型为A的对象。这是不可能的,因为A包含一个纯虚函数。(get_count())假设我尝试调用base.get_count()。
发布于 2014-01-08 06:33:54
方法virtual int get_count() const = 0;是纯虚拟。你不能创建一个抽象类的对象(或者换句话说--有一个纯虚拟成员)。如果要创建A的对象,请删除定义函数的= 0和(如果需要,可以使用空体):
virtual int get_count() const{};应该行得通。
发布于 2014-01-08 06:35:44
您实现A (如下所示)的方式使其成为一个抽象基类。
class A
{
int a;
public:
A() {}
virtual int get_count() const = 0; // this is a pure virtual function
int get_A() { return a; }
};它只能用作指向实现纯虚函数的派生类的指针:
int main()
{
B derived;
A* pA = new B; // this is okay
delete pA;
return 0;
}https://stackoverflow.com/questions/20983311
复制相似问题