将多态数据类型存储到 unique_ptr 向量中
Storing polymoprhic data types into a unique_ptr vector
我在尝试使用 Unique_ptr 向量构建程序来保存来自同一基 class 的多个 class 的数据时遇到问题。我很确定这个概念是正确的,所以我可以避免切片我的数据,但我不确定我到底做错了什么。另外我不确定我应该如何将 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.
更新:上面的代码可以正常编译和运行,但是该方法并不安全,并且可能导致整个程序出现严重错误。该程序是完全从头开始编写的,使用多个标准数组来保存单个 classes,而不是一个向量存储多个 classes。
这种使用向量的方法从一开始就存在缺陷,在确认分配信息中存在拼写错误后,使用更合理的方法从头开始重写项目。
我在尝试使用 Unique_ptr 向量构建程序来保存来自同一基 class 的多个 class 的数据时遇到问题。我很确定这个概念是正确的,所以我可以避免切片我的数据,但我不确定我到底做错了什么。另外我不确定我应该如何将 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.
更新:上面的代码可以正常编译和运行,但是该方法并不安全,并且可能导致整个程序出现严重错误。该程序是完全从头开始编写的,使用多个标准数组来保存单个 classes,而不是一个向量存储多个 classes。
这种使用向量的方法从一开始就存在缺陷,在确认分配信息中存在拼写错误后,使用更合理的方法从头开始重写项目。