我有一个包含多个方法的抽象基类。
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
的引用或指针。