C++ 通过引用传递对象的深度副本初始化结构
我正在为一个类分配任务,并且有一个链表,在每个节点中保存一个对象。节点被实现为结构。我在初始化对象时遇到问题,因为它似乎需要进行深度复制,但我没有。就我个人而言,我不知道如何把它做成一个深度复制品。每次删除原始对象时,名称和位置也会被删除 我知道同一个班级的其他学生也问过类似的问题,例如,但是我的代码是一样的,我最终还是遇到了问题 节点的构造如下所示:C++ 通过引用传递对象的深度副本初始化结构,c++,struct,initialization,C++,Struct,Initialization,我正在为一个类分配任务,并且有一个链表,在每个节点中保存一个对象。节点被实现为结构。我在初始化对象时遇到问题,因为它似乎需要进行深度复制,但我没有。就我个人而言,我不知道如何把它做成一个深度复制品。每次删除原始对象时,名称和位置也会被删除 我知道同一个班级的其他学生也问过类似的问题,例如,但是我的代码是一样的,我最终还是遇到了问题 节点的构造如下所示: List::Node::Node(const Winery& winery) : item(winery), nextB
List::Node::Node(const Winery& winery) :
item(winery),
nextByName(nullptr),
nextByRating(nullptr)
{
}
Winery::Winery(const char * const name, const char * const location, const int acres, const int rating) :
name(new char[strlen(name) + 1]),
location(new char[strlen(location) + 1]),
acres(acres),
rating(rating)
{
strcpy(this->name, name);
strcpy(this->location, location);
}
节点结构的定义:
struct Node
{
Node(const Winery& winery); // constructor
Winery item; // an instance of winery
// (NOT a pointer to an instance)
Node *nextByName; // next node in the name thread
Node *nextByRating; // next node in the rating thread
};
winery类的构造如下:
List::Node::Node(const Winery& winery) :
item(winery),
nextByName(nullptr),
nextByRating(nullptr)
{
}
Winery::Winery(const char * const name, const char * const location, const int acres, const int rating) :
name(new char[strlen(name) + 1]),
location(new char[strlen(location) + 1]),
acres(acres),
rating(rating)
{
strcpy(this->name, name);
strcpy(this->location, location);
}
我很确定这是一个深度复制,所以问题在于节点的构造,而不是winery。winery中需要一个复制构造函数。您显示的构造函数不是
item(winery)
使用的构造函数。另见:哇,谢谢,这正是我错过的。你能给我一个答案让我接受吗?