【发布时间】:2014-12-10 18:28:27
【问题描述】:
我的问题是:如何在继承的类中实现纯虚函数?它总是说我没有实现唯一的功能,但我试着去做。那么我的错误在哪里?
我的代码:
啊哈:
class A {
public:
A();
virtual std::pair<A*, A*> f1(const A& o) const=0;
virtual ~A();
};
B.h:
#include "A.h"
class B : public A {
public:
B();
virtual ~B();
virtual std::pair<A*, A*> f1(const A& o);
};
B.cpp:
#include "B.h"
B::B() : A() {}
B::~B() {}
std::pair<A*, A*> B::f1(const A& o) {
A* K1=new B();
A* K2=new B();
return std::make_pair (K1, K2);
}
我收到以下错误:
B.cpp: In member function ‘virtual std::pair<A*, A*> B::f1(const A&)’:
B.cpp:14:16: error: cannot allocate an object of abstract type ‘B’
A* K1=new B();
^
In file included from B.cpp:1:0:
B.h:4:7: note: because the following virtual functions are pure within ‘B’:
class B : public A {
^
In file included from B.h:1:0,
from B.cpp:1:
A.h:10:28: note: virtual std::pair<A*, A*> A::f1(const A&) const
virtual std::pair<A*, A*> f1(const A& o) const=0;
^
B.cpp:15:16: error: cannot allocate an object of abstract type ‘B’
A* K2=new B();
^
In file included from B.cpp:1:0:
B.h:4:7: note: since type ‘B’ has pure virtual functions
class B : public A {
^
还有:什么是正确的,A* K1=new A();或新的 B(); ?
【问题讨论】:
-
A::f1是一个const方法。您忘记了B类中方法末尾的const。 -
这就是为什么
override关键字很棒。
标签: c++ function inheritance virtual