练习13.18:
#include <iostream>
#include <string>
using namespace std;class Employee {private:static int sn;public:Employee() {mysn = sn++;}Employee(const string &s) {name = s;mysn = sn++;}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;f(a);f(b);f(c);return 0;
}
测试结果:
练习13.19:
如上题程序,当用a初始化b时,会调用拷贝构造函数。如果不定义拷贝构造函数,则合成的拷贝构造函数简单复制mysn,会使两者的序号相同。
当用b为c赋值时,会调用拷贝赋值运算符。如果不定义自己的版本,则编译器定义的合成版本会简单复制mysn,会使两者的序号相同。
#include <iostream>
#include <string>
using namespace std;class Employee {private:static int sn;public:Employee() {mysn = sn++;}Employee(const string &s) {name = s;mysn = sn++;}Employee (Employee &e) {name = e.name;mysn = sn++;}Employee &operator=(Employee &rhs) {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;f(a);f(b);f(c);return 0;
}
测试结果:
练习13.20:
暂时不会!!!
练习13.21:
暂时不会!!!