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

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

问题描述

在 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");
    }
};

这是一个可以接受的 C++ 解决方法吗?如果没有,有没有像 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 ?

感谢您阅读本文!

安东尼

推荐答案

你不能实例化抽象类,因此抽象类的向量不能工作.

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<AbstractClass>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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