gpt4 book ai didi

c++ - 无法使用 C++11 实例化抽象类

转载 作者:太空狗 更新时间:2023-10-29 20:26:37 24 4
gpt4 key购买 nike

为什么我不能在运行时像接口(interface)一样使用抽象类。

我得到输出:

1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(615): error C2259: 'Creature' : cannot instantiate abstract class
1> due to following members:
1> 'std::string Creature::Move(std::vector<std::string,std::allocator<_Ty>> &)' : is abstract
1> with
1> [
1> _Ty=std::string
1> ]

1> visual studio 2013\projects\cpp_demo\cpp_demo\creature.h(9) : see declaration of 'Creature::Move'
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(614) : while compiling class template member function 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)'
1> with
1> [
1> _Ty=Creature
1> ]

1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(752) : see reference to function template instantiation 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)' being compiled
1> with
1> [
1> _Ty=Creature
1> ]

1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\type_traits(580) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1> with
1> [
1> _Ty=Creature
1> ]

1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\vector(650) : see reference to class template instantiation 'std::is_empty<_Alloc>' being compiled
1> with
1> [
1> _Alloc=std::allocator<Creature>
1> ]

1> visual studio 2013\projects\cpp_demo\cpp_demo\main.cpp(7) : see reference to class template instantiation 'std::vector<Creature,std::allocator<_Ty>>' being compiled
1> with
1> [
1> _Ty=Creature
1> ]

我的代码:

int main()
{
unique_ptr<vector<Creature>> pCreatures(new vector<Creature>);

unique_ptr<Creature> pHuman(new Human());
pCreatures->push_back(*pHuman);
}



#include "stdafx.h"
#include "Creature.h"

class Human : public Creature
{
public:
virtual string Move(vector<string> &log);
};



#include "stdafx.h"
#include "IMove.h"

class Creature : public IMove
{
public:
virtual string Move(vector<string> &log) = 0;
virtual string GetState(vector<string> &log);
};

请帮忙。

最佳答案

您可以在 vector 或 unique_ptr 中使用抽象类,例如

#include <vector>
#include <memory>

using namespace std;

class Interface {
public:
virtual ~Interface() = 0;
};

Interface::~Interface() {}

class Implementation : public Interface {
};

int main(int argc, char** argv) {
unique_ptr<Interface> p(new Implementation);
vector<unique_ptr<Interface>> v;
v.emplace_back(new Implementation);
vector<Interface> vi;
// This leads to compile error: vi.emplace_back();
}

此外,您可以使用 vector<Interface>只要你不调用任何可能调用 new Interface 的方法.例如,如果您只声明一个变量 vector<Interface> v;它编译,但如果你 push_backemplace_backresize , 然后它会出现编译错误,因为它们会调用 new Interface .

以上代码是在gcc-4.6.3下测试的。

关于c++ - 无法使用 C++11 实例化抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com