gpt4 book ai didi

c++ - 如何管理对象之间的一对多关系? ( move 相关)

转载 作者:行者123 更新时间:2023-11-28 07:48:11 34 4
gpt4 key购买 nike

首先我想说我是 CPP 的新手(我从 cpp11 开始):)考虑以下实体:学生(名字+姓氏)和组(描述+更多学生)。我在 C++ 中创建了以下 2 个类:

class Student
{
private:
std::string firstName;
std::string lastName;
Student(const Student &student);
Student& operator=(const Student &student);
public:
Student():firstName(""), lastName("") { }
Student(std::string firstName, std::string lastName):firstName(firstName), lastName(lastName) { }
Student(const Student &&student):firstName(student.firstName), lastName(student.lastName) { }
Student& operator=(const Student &&student) { this->firstName=student.firstName; this->lastName=student.lastName; return *this; }
std::string GetFirstName() const { return this->firstName; }
std::string GetLastName() const { return this->lastName; }
};


class Group
{
private:
std::string description;
std::vector<std::shared_ptr<Student>> students;
Group(const Group &group);
Group& operator=(const Group &group);
public:
explicit Group():description(""), students(std::vector<std::shared_ptr<Student>>()) { }
explicit Group(std::string description) :description(description), students(std::vector<std::shared_ptr<Student>>()) { }
void NewStudent(Student &&student) { students.push_back(std::make_shared<Student>(std::move(student))); }
std::vector<std::shared_ptr<Student>> GetStudents() const { return students; }
};

主要是我有这个:

Student s1("fn1","ln1");
Student s2("fn2","ln2");
//Student s3("fn3","ln3");
Group cppGroup("C plus plus");
cppGroup.NewStudent(std::move(s1));
cppGroup.NewStudent(std::move(s2));
cppGroup.NewStudent(Student("fn3", "ln3"));
//cppGroup.NewStudent(s3);
std::vector<std::shared_ptr<Student>> cppStudents=cppGroup.GetStudents();

我的问题与 NewStudent 方法有关。在前两种情况下,参数是 move(s),在第三种情况下,参数是 Student(...)。我的猜测是 Student("fn3", "ln3") 与 Student s3("fn3, "ln3") 相同,但如果我将 s3 传递给该函数,它就不会编译并出现以下错误:无法从 Student 转换为 Student&&

PS:如果您能帮助我理解如何制作我认为理想的示例,我将不胜感激。非常感谢。

LE:我想我明白发生了什么,Visual Studio 显示以下错误:无法将左值转换为右值 所以我猜如果我传递给 NewStudent s3 它不知道如何将它转换为右值,但如果我将它传递给 Student("fn3", "ln3") if 将调用 move 构造函数。

最佳答案

如果这确实是您的设计,您可以大大简化它并取消所有智能指针和自定义结构:

class Student
{
private:
std::string firstName;
std::string lastName;
public:
Student(std::string firstName, std::string lastName):firstName(firstName), lastName(lastName) { }
std::string GetFirstName() const { return this->firstName; }
std::string GetLastName() const { return this->lastName; }
};


class Group
{
private:
std::string description;
std::vector<Student> students;
public:
explicit Group(std::string description) :description(description) { }
void NewStudent(Student student) { students.push_back(student); }
std::vector<Student> GetStudents() const { return students; }
};

关于c++ - 如何管理对象之间的一对多关系? ( move 相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419817/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com