将多态数据类型存储到unique_ptr向量中

时间:2015-03-13 22:56:11

标签: c++ vector polymorphism function-pointers unique-ptr

我在尝试使用Unique_ptr向量构建程序时遇到问题,该向量用于保存来自同一基类的多个类的数据。我很确定这个概念是正确的,所以我可以避免切片我的数据,但我不确定我在这里做错了什么。另外我不确定我应该如何将unique_ptr传递给函数来读取或写入它。任何帮助将不胜感激。 (编辑,使代码实际上易于理解,对不起!)

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;


class Base
{
public:
    Base();
    Base(int x, int y, string z) :Z(z), Y(y), X(x){}
    virtual void printstuff(){cout << X << Y << Z; system("pause"); }
    virtual ~Base(){}
protected:
    int X, Y;
    string Z;
};

class Derrived : public Base
{
public:
    Derrived();
    Derrived(int x, int y, string z, int a, int c) : Base(x, y, z), changeable(c), A(a){}
    virtual void printstuff(){cout << X << Y << Z << changeable << A;}
    int changeable;
    ~Derrived(){}
private:
    int A;
};

void otherfunction(vector<unique_ptr<Base>>&);

void main()
{
    vector<unique_ptr<Base>> array1;
    array1.emplace_back(new Derrived (1, 2, "check", 3, 5));
    otherfunction(array1);
    array1[0]->printstuff();
    system("pause");
}



void otherfunction(vector<unique_ptr<Base>>& var1)
{
    dynamic_cast<Derrived &>(*var1[0]).changeable = 3;
}

我希望输出语句为3可更改,我出于某种原因得到错误C2664所以我不确定我究竟做错了什么,因为它没有在我的代码中引用一个特定的行(它引用的行是xmemory.h的第600行)。可以在此处找到实际代码的副本:Link to the actual code.

更新:上面的代码编译并正常运行,但是该方法不过是安全的,并且可能导致整个程序出现严重错误。该程序完全是从头开始编写的,使用多个标准数组来保存单个类,而不是一个存储多个类的向量。

1 个答案:

答案 0 :(得分:0)

这种使用向量的方法在开始时存在缺陷,在验证分配信息中存在拼写错误后,使用更合理的方法从头开始重写项目。