C ++继承纯虚函数

时间:2014-12-10 18:28:28

标签: c++ function inheritance virtual

我的问题是:如何在继承的类中实现纯虚函数?它总是说我没有实现唯一的功能,但我试图这样做。那我的错误在哪里?

我的代码:

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 =新的A();或新的B(); ?

3 个答案:

答案 0 :(得分:2)

您的覆盖必须与cv-qualification匹配。你在这里错过了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

答案 1 :(得分:2)

允许&#39;把这两个并排放在一起看看:

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。他们以后会预防头痛。

答案 2 :(得分:2)

在B中,您的功能必须是virtual std::pair<A*, A*> f1(const A&) const;,或者它是一个不同的功能,而不是覆盖A中的功能。

(如果您正在使用C ++ 11编译器,请执行std::pair<A*, A*> f1(const A&) const override;,并且读者会清楚您想要覆盖该函数。)

相关问题