我有这门课:
#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(...)
函数)设置为 vector 中包含的前一个元素?
get_parents()
函数也可以定义为:
void get_parents(person* mother, person* father)
或
void get_parents(unique_ptr<person> mother, unique_ptr<person> father)
谢谢你的建议
最佳答案
有一个唯一的指针,因此该指针在任何时候最多只在一个地方。您有超过 1 个引用(在 vector 中,如果是父亲或母亲,则可能在人中)。
你可能想看看使用共享指针和弱指针: http://en.cppreference.com/w/cpp/memory/shared_ptr http://en.cppreference.com/w/cpp/memory/weak_ptr
关于c++ - vector<unique_ptr<myclass>> 元素之间的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37345791/