c++ - 纯虚函数和 "cannot allocate an object"

标签 c++ inheritance

<分区>

我有一个包含多个方法的抽象基类。

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' 中是纯函数:"

main.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()

最佳答案

编辑:

在你添加错误消息后,我在一个干净的 C++ 项目上测试了你的代码,你的代码示例工作正常。

========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

基础.h

#pragma once
class Base
{

private:
    virtual void example_1() = 0;
    virtual void example_2() = 0;

public:
    Base();
    ~Base();
};

基础.cpp

#include "Base.h"


Base::Base()
{
}


Base::~Base()
{
}

例子.h

#pragma once

#include "Base.h"

class Example : public Base
{
public:

    virtual void example_1();
    virtual void example_2();

    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 是一个具有 2 个纯虚函数的类 -> Base 是一个抽象类。

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

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

关于c++ - 纯虚函数和 "cannot allocate an object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475470/

相关文章:

python - 使用 Pybind11 将 C++ 扩展到 Python

c++ - 简单的 std::sort 不工作

Delphi T字典继承

java - 是否可以在父类(super class)对象上调用子类的方法?

c++ - 运行时绑定(bind)和虚拟继承

c++ - 如何将 c++ std::shared_ptr 包装在包装器头文件中以便可以从 c 中调用它?

使用 string.length() 作为 for 循环结尾时,C++ 字符串下标超出范围

c++ - 并行字数统计

Java:只能由父类(super class)调用的方法

c# - 字符串或其他密封类的强类型