1

这是列表类中节点的构造函数。我需要制作一个酒厂的深层副本,这是初始化列表中的另一个类。项目是酒厂的一个实例。

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;
}
4

1 回答 1

2

在 Node-ctor 中复制酒厂三遍绝对没有道理。
一次就够了:

List::Node::Node(const Winery& winery) : item(winery) {}

不过,您可以添加一个 move-ctor(C++11 及更高版本):

List::Node::Node(Winery&& winery) : item(std::move(winery)) {}

类似的Winery
如果这四个都是成员,那么Winery-ctor 已经做了一个深拷贝。

我希望你记得规则 3 并且还提供了一个自定义的 copy-ctor、copy-assignment-operator 和 dtor。
不过,最好使用std::unique_ptror 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)
{}
于 2014-10-11T04:15:09.713 回答