让我们来分析下面这段代码:
#include <iostream>
#include <string>
using namespace std;class Employee {private:static int sn;public:Employee() {cout << "Employee()" << endl;mysn = sn++;}Employee(const string &s) {cout << "Employee(const string &s)" << endl;name = s;mysn = sn++;}Employee (Employee &e) {cout << "Employee (Employee &e)" << endl;name = e.name;mysn = sn++;}Employee &operator=(Employee &rhs) {cout << "Employee &operator=(Employee &rhs)" << endl;name = rhs.name;return *this;}const string &get_name() {return name;}int get_mysn() {return mysn;}private:string name;int mysn;
};int Employee::sn = 0;void f(Employee &s) {cout << s.get_name() << " " << s.get_mysn() << endl;
}int main() {Employee a("赵"), b = a, c;c = b;Employee d = c;Employee e;e = c;f(a);f(b);f(c);f(d);f(e);return 0;
}
测试结果:
-
Employee(“赵”):调用了Employee(const string &s)
-
Employee b = a 调用了Employee (Employee &e),可以看成Employee b(a),如果我们将Employee b = a改成:Employee b(a);也是调用Employee (Employee &e)
-
Employee c 调用了Employee()
-
c = b;调用了Employee &operator=(Employee &rhs)
-
Employee d = c;调用了Employee (Employee &e),可以看成Employee d( c ),如果我们将Employee d = c改成Employee d( c ),也是调用Employee (Employee &e)
-
Employee e;调用了Employee()
-
e = c;调用了Employee &operator=(Employee &rhs)
如有错误,请在评论区留言指正一下,谢谢 !!!