まず第一に、私は 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 メソッドに関連しています。最初の 2 つのケースではパラメーターは move(s) で、3 番目のケースでは Student(...) です。私の推測では、 Student("fn3", "ln3") は Student s3("fn3, "ln3") と同じですが、関数に s3 を渡すと、次のエラーでコンパイルされません: cannot convert from学生から学生へ&&
PS: 私が理想と考える例を作成する方法を理解するのを手伝ってくれれば幸いです。どうもありがとうございました。
LE: 何が起こっているのか理解していると思います.Visual Studio は次のエラーを示しています:左辺値を右辺値に変換できません.移動コンストラクターを呼び出す場合は、 Student("fn3", "ln3") を渡します。