1

これは、リスト クラスのノードのコンストラクタです。初期化リストの別のクラスである winery のディープ コピーを作成する必要があります。アイテムはワイナリーのインスタンスです。

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 でワイナリーを 3 回コピーする理由はまったくありません。
一回だけで十分です:

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

ただし、move-ctor を追加することもできます (C++11 以降):

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

についても同様ですWinery
これらの 4 つがすべてのメンバーである場合、Winery-ctor は既にディープ コピーを実行しています。

ルール オブ 3 を覚えていて、カスタムの copy-ctor、copy-assignment-operator、および dtor を提供していただければ幸いです。それでも、または
を使用する方がよいでしょう。std::unique_ptrstd::string

また、最上位の cv-qualifiers は役に立たないので、削除しました。

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 に答える