练习13.18
定义一个Employee类,它包含雇员的姓名和唯一的雇员证号。为这个类定义默认构造函数,以接受一个标识雇员姓名的string的构造函数。每个构造函数应该通过递增一个static数据成员来生成一个唯一的证号。
解答:
#include <string>
#include <iostream>
using namespace std;
class Employee{
public:
string name;
static int ID;
Employee();
Employee(const string&);
Employee(Employee &emp) { ++ID; name = emp.name; }
string GetName(){ return name; }
int GetID(){ return ID; }
};
int Employee::ID = 0;
Employee::Employee()
{
++ID;
name = "SB";
}
Employee::Employee(const string& nam)
{
++ID;
name = nam;
}
int main()
{
Employee E1;
cout << E1.GetName() << endl;
cout << E1.GetID() << endl;
Employee E2("C++!");
cout << E2.GetName() << endl;
cout << E2.GetID() << endl;
Employee E3;
E3 = E2;
cout << E3.GetName() << endl;
cout << E3.GetID() << endl;
Employee E4(E2);
cout << E4.GetName() << endl;
cout << E4.GetID() << endl;
return 0;
}
<img src="https://img-blog.csdn.net/20150606155610944" alt="" />
本实验证明以下几点:
1.类的静态成员 在类内声明,在类外初始化,且一定要初始化,不然运行将出错。
2.合成拷贝构造函数只是 对被拷贝对象的简单复制。本例中去掉自定义的拷贝构造函数后,E3 和 E4 的输出结果将变得相同:在初始化E3的时候 调用默认构造函数,ID+1;但当E4用E2进行合成的拷贝构造时,系统仅是简单的拷贝。没有增加ID的值。
练习 13.1.19
你的Employee类需要定义它自己的拷贝控制成员吗?如果需要,为什么?如果不需要,为什么?实现你认为Employee需要的拷贝控制成员。
解答:
需要拷贝构造,上述分析已经说明。
练习13.20
解释当我们拷贝、赋值或销毁TextQuery和QueryResult类(参见12.3节,430页)对象时会发生什么。
解答:
文本查询程序尚未学习,此题留待将来
练习13.22
假定我们希望HasPtr的行为想一个值。即,对于对象所指向的string成员,每个对象都有一份自己的拷贝。我们将在下一节介绍拷贝控制成员的定义。但是,你已经学习了定义这些成员所需要的所有知识。在继续学习下一章之前,为HasPtr编写拷贝构造函数和拷贝赋值运算符
解答:
class HasPtr {
public:
HasPtr(const string &s = string()) :
ps(new string(s)), i(0){}
HasPtr operator=(const HasPtr &ori){
ps = new string(*(ori.ps));
i = ori.i;
return *this;
}
HasPtr(const HasPtr& has)
{
ps = new string(*(has.ps));
i = has.i;
}
string *ps;
int i;
};