首先我想说我对 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 传递给函数,它将无法编译并出现以下错误:无法从学生对学生&&
PS:如果您帮助我了解如何制作我认为理想的示例,我将不胜感激。非常感谢你。
LE:我想我明白发生了什么,Visual Studio 显示以下错误:无法将左值转换为右值,所以我的猜测是,如果我传递给 NewStudent s3,它不知道如何将其转换为右值,但如果我如果将调用移动构造函数,则传递它 Student("fn3", "ln3")。