同じクラスから作られたインスタンス同士を代入してみます。
(構造体でも結果は同じです)
まずは適当なクラスを作って、コンストラクタで初期化し、値を表示してみます。
#include <iostream> #include <string> using std::string; using std::cout; using std::endl; class student { string m_name; string m_student_id; int m_age; public: student(){}; student(string _name, string _id, int _age); void printMe(); }; student::student(string _name, string _id, int _age) { m_name = _name; m_student_id = _id; m_age = _age; } void student::printMe() { cout << "~~~~~~~~my profile~~~~~~~~~~" << endl; cout << "Name :" << m_name << endl; cout << " ID :" << m_student_id << endl; cout << " Age :" << m_age << endl; cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl; } int main() { student s1("yamada", "001", 18); student s2("sato", "002", 21); student s3; student s4; //まず普通に山田さんを表示 s1.printMe(); return 0; }
~~~~~~~~my profile~~~~~~~~~~ Name :yamada ID :001 Age :18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
それでは、値を初期化していないインスタンスに“山田さん”を代入してみます。
int main() { student s1("yamada", "001", 18); student s2("sato", "002", 21); student s3; student s4; //まず普通に山田さんを表示 s1.printMe(); //初期化されていないインスタンスs3を表示 s3.printMe(); return 0; }
実行結果
~~~~~~~~my profile~~~~~~~~~~ Name :yamada ID :001 Age :18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~my profile~~~~~~~~~~ Name : ID : Age :0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
インスタンスs3のメンバ変数は中身が空っぽなのがわかります。(ちょっと語弊あるかもだけど。。。)
それでは代入。
int main() { student s1("yamada", "001", 18); student s2("sato", "002", 21); student s3; student s4; //まず普通に山田さんを表示 s1.printMe(); //初期化されていないインスタンスs3を表示 s3.printMe(); //s3にs1を代入 s3 = s1; s1.printMe(); s3.printMe(); return 0; }
~~~~~~~~my profile~~~~~~~~~~ Name :yamada ID :001 Age :18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~my profile~~~~~~~~~~ Name : ID : Age :0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~my profile~~~~~~~~~~ Name :yamada ID :001 Age :18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~my profile~~~~~~~~~~ Name :yamada ID :001 Age :18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
山田さんが2匹に増えているのがわかります。
このように、同じクラスから作られたインスタンス同士は、代入することができます。
ただし、注意が必要な場合(メンバにポインタやアドレスを含むクラスなど)があります。