【问题标题】:'Cannot instantiate abstract class' although class shouldn't be abstract'不能实例化抽象类'虽然类不应该是抽象的
【发布时间】:2013-08-23 14:42:26
【问题描述】:

所以我有两节课。一个只有纯虚函数。另一个实现了这些功能,并且是从第一个类派生的。 我知道我无法实例化第一堂课。但是当我尝试创建第二类的对象时,它也会失败。

这就是我的第二堂课的总体情况:

class SecondClass  : public FirstClass
{
public:
     SecondClass();
virtual ~SecondClass(void);

void Foo();
void Bar();

}

实施:

SecondClass::SecondClass()
{...}
SecondClass::~SecondClass(void)
{...}
void SecondClass::Foo()
{...}
void SecondClass::Bar()
{...}

这就是我实例化它并得到错误的方式:

SecondClass mSecClass;

我哪里错了?

FirstClass.h

class FirstClass
{
public:
  FirstClass(void);
  virtual ~FirstClass(void);

  virtual void Foo() = 0;
  virtual void Bar() = 0;
};

【问题讨论】:

  • 显示FirstClass的界面!如果没有看到它的声明,就无法判断SecondClass 是否是抽象的。
  • FirstClass 声明,请 :)
  • 对不起,我添加了它 =)
  • 复制/粘贴,不要尝试手动输入。您发布的 FirstClass 无法编译,因为您尝试将析构函数命名为 ~SecondClass
  • 提示:在覆盖虚函数时使用override,并阅读错误信息;所有半体面的编译器都会告诉您在您尝试实例化的类中哪些函数是纯函数。

标签: c++ abstract-class


【解决方案1】:

您需要定义~FirstClass() 析构函数并省略其构造函数

class FirstClass
{
public:
  virtual ~FirstClass(void) {} // or use C++11 = default syntax

  virtual void Foo() = 0;
  virtual void Bar() = 0;
};

class SecondClass  : public FirstClass
{
public:
     SecondClass();
virtual ~SecondClass(void);

void Foo();
void Bar();

};

SecondClass::SecondClass() {}
SecondClass::~SecondClass(void) {}
void SecondClass::Foo() {}
void SecondClass::Bar() {}

int main()
{
        SecondClass mSecClass;
}

Live Example

【讨论】:

  • 添加第一类析构函数是对的,如果有链接错误,假设修复链接错误。但是,我不确定该链接如何指向对象初始化错误?
【解决方案2】:

定义你声明的每个函数,除了纯虚函数(virtual void foo() = 0)。 试试下面的代码:

#include<iostream>

using namespace std;

class FirstClass
{
public:
    FirstClass()
    {
        //
    }
    virtual ~FirstClass();
    virtual void Foo();
    virtual void Bar();
};
    FirstClass::~FirstClass()
    {
        //
    }
    void FirstClass::Foo()
    {
        //
    }
    void FirstClass::Bar()
    {
        //
    }




class SecondClass  : public FirstClass
{
public:
     SecondClass();
virtual ~SecondClass(void);

void Foo();
void Bar();

};

SecondClass::SecondClass(){
//
}
SecondClass::~SecondClass(void)
{//
}
void SecondClass::Foo()
{//
}
void SecondClass::Bar()
{//
}

int main()
{
    SecondClass name;
    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2013-03-07
    • 2016-09-21
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多