13.1.6
来源:互联网 发布:手机文档解密软件 编辑:程序博客网 时间:2024/06/05 11:00
练习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="http://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;};
0 0
- 13.1.6
- 13.1.6
- 算法导论 练习题 13.1-6
- 13.1
- 13.1
- 13.1
- DevExpress昨天发布13.1.6版本
- 第十三章 13.1.6节练习 & 13.2节练习
- 检查点13.1
- * eg-13.1
- 实验13.1
- 13.1 Triangle
- 13.1.3
- 13.1.1
- 13.1.2
- 13.1.4
- centos 6 python3 安装 Collecting Twisted>=13.1.0 (from Scrapy) Could not find a version that satisf
- 13.1 Implicit conversions
- 五子棋AI算法浅谈
- 慎用Outline ,UGUI Outline实现原理分析
- 380多个梦想的力量
- java http get、post方式
- Qt5.4连接MySql
- 13.1.6
- Balanced Binary Tree
- 建立一个堆结构heap-build
- cocos2d-x lua table与json的转换
- iOS UILabel自动换行,自适应高度
- cmake学习(一)静态库与动态库构建
- C语言字符串操作函数
- 每日一题G
- leetcode--Rotate Image