【问题标题】:C++ Inheritance pure virtual functionsC++ 继承纯虚函数
【发布时间】: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


【解决方案1】:

让我们把这两个并排,仔细看看:

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】:

    您的覆盖必须与 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
    

    【讨论】:

      【解决方案3】:

      在 B 中,您的函数必须是 virtual std::pair&lt;A*, A*&gt; f1(const A&amp;) const; 或者它是不同的函数,而不是覆盖 A 中的函数。

      (如果您使用的是 C++11 编译器,请执行std::pair&lt;A*, A*&gt; f1(const A&amp;) const override;,读者会清楚您打算覆盖该函数。)

      【讨论】:

        猜你喜欢
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        • 2012-08-06
        • 2018-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-31
        相关资源
        最近更新 更多