这是list类中节点的构造函数。我需要做一个酒厂的深刻副本,在初始化列表中的另一个类。物品是酿酒厂的一个例子。
List::Node::Node(const Winery& winery) :
item(winery)
// your initialization list here
{
Winery w = winery;
item = w;
}酿酒厂的构造师:
Winery::Winery(const char * const name, const char * const location,
const int acres, const int rating) :
name(name),
location(location),
acres(acres),
rating(rating)
{
char *nm = new char[strlen(name) + 1];
char *loc = new char[strlen(location) + 1];
strcpy(nm, this->name);
strcpy(loc, this->location);
this->name = nm;
this->location = loc;
this->acres = acres;
this->rating = rating;
}发布于 2014-10-11 04:15:09
在酒庄里复制三次绝对没有任何结果。
一次就够了:
List::Node::Node(const Winery& winery) : item(winery) {}不过,您可以添加一个移动ctor (C++11及更高版本):
List::Node::Node(Winery&& winery) : item(std::move(winery)) {}类似于Winery。
如果这四个成员都是成员,那么Winery-ctor已经做了一个深拷贝。
我希望你能记住第3条规则,并且还提供了一个定制的拷贝机、拷贝赋值操作符和dtor.
不过,最好还是使用std::unique_ptr或std::string。
此外,顶级cv-限定符是无用的,因此我删除了它们。
Winery::Winery(const char * name, const char * location,
int acres, int rating) :
name(strcpy(new char[strlen(name)+1], name),
location(strcpy(new char[strlen(location)+1], location),
acres(acres),
rating(rating)
{}https://stackoverflow.com/questions/26310837
复制相似问题