我的问题是:如何在继承的类中实现纯虚拟函数?它总是说我没有实现唯一的函数,但我试着去做。那我的错误在哪里?
我的代码:
A.h:
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();?
发布于 2014-12-10 18:32:20
让我们把这两件事并排放在一起,仔细看:
A: virtual std::pair<A*, A*> f1(const A& o) const=0;
B: virtual std::pair<A*, A*> f1(const A& o);我看到了一个不同之处,其中一个是const函数,另一个不是。这就产生了两种不同的功能。由于const函数从未重载,所以B仍然是抽象的,就像A一样,不能实例化。
A* K1 = new A(); //would give you an A, if A weren't abstract. Do you want an A or B?
A* K1 = new B(); //gives a B object, stored as a pointer to an A interface.我还强烈建议在当前拥有原始指针的地方使用std::unique_ptr。他们以后会预防头痛。
发布于 2014-12-10 18:32:13
你的覆盖必须符合简历的条件。你错过了一个const:
std::pair<A*, A*> B::f1(const A& o) /* [const] */由于它不覆盖,而且基类方法是纯虚拟的,因此派生类变得抽象。不能实例化抽象类型的对象。
您必须将const添加到声明和定义中。此外,要确保重写,请使用关键字override。
std::pair<A*, A*> f1(const A& o) override; // error since it does not override发布于 2014-12-10 18:32:58
在B中,您的函数需要是virtual std::pair<A*, A*> f1(const A&) const;,或者是不同的函数,而不是覆盖A的函数。
(如果您使用的是C++11编译器,请执行std::pair<A*, A*> f1(const A&) const override;,读者可以清楚地看到您打算重写该函数。)
https://stackoverflow.com/questions/27408254
复制相似问题