为什么我们不能声明一个std :: vector< AbstractClass&gt ;? [英] Why can't we declare a std::vector<AbstractClass>?

查看:345
本文介绍了为什么我们不能声明一个std :: vector< AbstractClass&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中花了很多时间,我注意到,如果你声明一个抽象类,以使用它作为一个接口,你不能实例化这个抽象类的向量来存储孩子类的实例。

Having spent quite some time developping in C#, I noticed that if you declare an abstract class for the purpose of using it as an interface you cannot instantiate a vector of this abstract class to store instances of the children classes.

#pragma once
#include <iostream>
#include <vector>

using namespace std;

class IFunnyInterface
{
public:
    virtual void IamFunny()  = 0;
};

class FunnyImpl: IFunnyInterface
{
public:
    virtual void IamFunny()
    {
        cout << "<INSERT JOKE HERE>";
    }
};

class FunnyContainer
{
private:
    std::vector <IFunnyInterface> funnyItems;
};

在MS VS2005中声明抽象类向量的行会导致此错误:

The line declaring the vector of abstract class causes this error in MS VS2005:

error C2259: 'IFunnyInterface' : cannot instantiate abstract class

我看到一个显而易见的解决方法,即用以下代替IFunnyInterface:

I see an obvious workaround, which is to replace IFunnyInterface with the following:

class IFunnyInterface
{
public:
    virtual void IamFunny()
    {
        throw new std::exception("not implemented");
    }
};




如果没有,是否有任何第三方库,如boost,可以帮助我解决这个问题?

Is this an acceptable workaround C++ wise ? If not, is there any third party library like boost which could help me to get around this ?

感谢您阅读!

Anthony

推荐答案

您不能实例化抽象类,

You can't instantiate abstract classes, thus a vector of abstract classes can't work.

然而,您可以使用指针向量来抽象类:

You can however use a vector of pointers to abstract classes:

std::vector<IFunnyInterface*> ifVec;

这也允许你实际使用多态行为 - 即使该类不抽象,值会导致对象切片的问题。

This also allows you to actually use polymorphic behaviour - even if the class wasn't abstract, storing by value would lead to the problem of object slicing.

这篇关于为什么我们不能声明一个std :: vector&lt; AbstractClass&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆