我有这个类:
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class person
{
public:
person(string name, string surname):_name(name), _surname(surname){}
virtual ~person(){}
void print()
{ cout << _name << ' ' << _surname << endl
<< "mother: " << _mother->get_name() << ' ' << _mother->get_surname() << endl
<< "father: " << _father->get_name() << ' ' << _father->get_surname() << endl;
}
string get_name(){return _name;}
string get_surname(){return _surname;}
void set_parents(person &mother, person &father)
{
_mother = unique_ptr<person>(&mother);
_father = unique_ptr<person>(&father);
}
private:
string _name, _surname;
unique_ptr<person> _mother, _father;
};
然后是主函数:
int main()
{
vector<unique_ptr<person> > people;
vector<unique_ptr<person> >::iterator iter;
people.push_back(unique_ptr<person>(new person("Marisa", "Miller")));
people.push_back(unique_ptr<person>(new person("Andrew", "Clark")));
people.push_back(unique_ptr<person>(new person("Thomas", "Clark")));
people.push_back(unique_ptr<person>(new person("Elisa", "Clark")));
people.push_back(unique_ptr<person>(new person("Edward", "Drake")));
people.push_back(unique_ptr<person>(new person("Jhon", "Drake")));
// here is the problem:
people.at(2).set_parents(???)
for(iter = people.begin(); iter != people.end(); ++iter)
{
(*iter)->print();
}
return 0;
}
通过指针,我将定义以下家谱:
[Marisa Miller] [Andrew Clark]
| |
+---------+---------+
|
+--------------[Thomas Clark]
|
+--------------[Elisa Clark] [Edward Drake]
| |
+---------+---------+
|
[Jhon Drake]
问题是:如何将指针(_mother
和_father
,通过get_parents(...)
函数)设置为向量中包含的前一个元素?get_parents()
函数也可以定义为:
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_ptrhttp://en.cppreference.com/w/cpp/memory/weak_ptr
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
成员函数(在缺少父级的情况下它会崩溃)。