2016-05-20 10 views
1

私は、このクラスを持っているポインタ<unique_ptrを<myclass>>要素

[Marisa Miller]  [Andrew Clark] 
     |     | 
     +---------+---------+ 
        | 
        +--------------[Thomas Clark] 
        | 
        +--------------[Elisa Clark]  [Edward Drake] 
             |     | 
             +---------+---------+ 
               | 
              [Jhon Drake] 

質問は どうすればポインタを設定できますか(_mother_fatherget_parents(...)の関数)をベクトルに含まれる前の要素に置き換えますか? get_parents()機能もとして定義することができる。ポインタのみで、ほとんどの一つの場所にであるように、任意の提案

答えて

0

ユニークなポインタのおかげではあり

void get_parents(person* mother, person* father) 

または

void get_parents(unique_ptr<person> mother, unique_ptr<person> father) 

すべての時間。あなたは1つ以上の参照を持っています(ベクトルで、おそらく人の中で、それが父または母親の場合)。

あなたは共有ポインタと弱いポインタを使用して見たいと思うかもしれません: http://en.cppreference.com/w/cpp/memory/shared_ptr http://en.cppreference.com/w/cpp/memory/weak_ptr

0

person_mother_fatherを所有していなければなりません。

これはおそらく良いです:

// ... 
private: 
    std::string _name, _surname; 
    person *_mother; 
    person *_father; 
}; // class person 

あなたは(つまり、コンテナはその要素を所有している)std::vector<std::unique_ptr<person>> people;を続けるならば、あなたは書くことができます:

void person::set_parents(person &mother, person &father) 
{ 
    _mother = &mother; 
    _father = &father; 
} 

people[2]->set_parents(*people[0], *people[1]); 
people[3]->set_parents(*people[0], *people[1]); 
people[5]->set_parents(*people[3], *people[4]); 

も(それがクラッシュperson::printメンバ関数を修正両親がいない場合)。

関連する問題