纯虚拟功能和"cannot allocate an object"

Pure virtual function and "cannot allocate an object"

本文关键字:allocate an object cannot 功能 虚拟      更新时间:2023-10-16

我有一个带有几个方法的基本抽象类。

base.h
class Base 
{
..
..
virtual void example_1() = 0;
virtual void example_2() = 0;
};
example.h
class Example : public Base
{
virtual void example_1();
virtual void example_2();
};
example.c
void Example :: example_1()
{
cout << "1";
}
void Example :: example_2()
{
cout << "2";
}
纯虚函数必须在派生类中实现,我已经这样做了。但我仍然不清楚为什么我得到这个错误

错误"无法分配抽象类型" Example "的对象": Example .h 27:7:注意:因为以下虚函数在'Example'中是纯的:"

c: 225:25:

error: cannot allocate an object of abstract type 'Example'
In file included from main.c:328:0:
example.h:27:7: note: because the following virtual functions are pure within 'Example':
base.h:150:18: note:  virtual void Base::example_1()
base.h:151:18: note:  virtual void Base::example_2()

Edit:

在你添加了错误信息后,我在一个干净的c++项目上测试了你的代码,你的代码示例运行良好。

========== 构建:1成功,0失败了,最新的,0跳过 ==========

Base.h

#pragma once
class Base
{
private:
    virtual void example_1() = 0;
    virtual void example_2() = 0;
public:
    Base();
    ~Base();
};

Base.cpp

#include "Base.h"

Base::Base()
{
}

Base::~Base()
{
}

Example.h

#pragma once
#include "Base.h"
class Example : public Base
{
public:
    virtual void example_1();
    virtual void example_2();
    Example();
    ~Example();
};

Example.cpp

#include "Example.h"
#include <iostream>
using namespace std;
Example::Example()
{
}

void Example::example_1()
{
    cout << "1";
}
void Example::example_2()
{
    cout << "2";
}
Example::~Example()
{
}

Main.cpp

#include "Example.h"

int main()
{
    Example ex;
    ex.example_1();
    return 0;
}

尝试将文件名从*.c更改为*.cpp在一个干净的项目中检查有问题的代码


你没有提供关于你的错误的完整信息,所以我猜这就是你正在处理的场景:

int main()
{
  // Cannot instantiate, Base is abstract
  Base base1;
  // Should work
  Example example;
  // Should work
  Base* base2 = new Example();
  return 0;
}

在你的例子中,Base是一个有两个纯虚函数的类-> Base是一个抽象类。

因此你不能创建Base的实例。

你可以创建一个Example的实例,也可以有一个指向Base的引用或指针。