cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Walker 123 更新时间:2023-11-28 07:48:11 34 4
mua khóa gpt4 Nike

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

class Student
{
riêng tư:
std::string firstName;
std::string lastName;
Student(const Student &student);
Student& operator=(const Student &student);
công cộng:
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
{
riêng tư:
std::string description;
std::vector<>> students;
Group(const Group &group);
Group& operator=(const Group &group);
công cộng:
explicit Group():description(""), students(std::vector<>>()) { }
explicit Group(std::string description) :description(description), students(std::vector<>>()) { }
void NewStudent(Student &&student) { students.push_back(std::make_shared(std::move(student))); }
std::vector<>> 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<>> 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 构造函数。

câu trả lời hay nhất

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

class Student
{
riêng tư:
std::string firstName;
std::string lastName;
công cộng:
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
{
riêng tư:
std::string description;
std::vector students;
công cộng:
explicit Group(std::string description) :description(description) { }
void NewStudent(Student student) { students.push_back(student); }
std::vector GetStudents() const { return students; }
};

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

34 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress