拷贝构造函数
来源:互联网 发布:c语言字符数组赋值 编辑:程序博客网 时间:2024/05/16 12:04
拷贝构造函数的作用是根据已存在的对象创建一个新的对象作为这个对象的副本。
Teacher Mrwang(”chenliaongqiao“);Teacher MissJia(Mrwang);//创建副本
拷贝构造函数的参数是这个类的对象的引用。
仅当涉及到拷贝指针型属性的时候需要自己添加拷贝构造函数。在拷贝构造函数中,要完成指针类型成员的拷贝,并不能直接采用内存拷贝的形式,那样只是拷贝了指针的值,指针指向的内容并没有得到拷贝。要完成拷贝,首先要得到已有对象的属性,获得它所指向的对象,然后以这个对象为蓝本,利用keyboard类的默认构造函数创建这个keyboard的副本。
实例:
copy.h
#ifndef Copy#define Copy#include <string.h>using namespace std;struct Keyboard {string m_strModel;};class Computer{public:Computer():m_pKeyboard(NULL) {}Computer(const Computer &com):m_strModel(com.m_strModel) { Keyboard * OldKeyboard=com.GetKeyboard(); //创建一个新的类对象赋值给m_pKeyboard if(NULL!= OldKeyboard) m_pKeyboard=new Keyboard(*(OldKeyboard)); else m_pKeyboard=NULL; }void SetKeyboard(Keyboard* pkeyboard) { m_pKeyboard= pkeyboard; }Keyboard* GetKeyboard () const { return m_pKeyboard; }private:Keyboard * m_pKeyboard;string m_strModel;};#endif
main.cpp
#include <assert.h>#include <iostream>#include "copy.h"#include <string>using namespace std;int main(){ Computer oldcom; Keyboard keyboard; keyboard.m_strModel ="dou"; oldcom.SetKeyboard(&keyboard); Computer newcom(oldcom); assert(newcom.GetKeyboard()!= oldcom.GetKeyboard()); assert(newcom.GetKeyboard()-> m_strModel != oldcom.GetKeyboard()-> m_strModel); return 0;}
在main函数中, assert(newcom.GetKeyboard()!= oldcom.GetKeyboard());处正常,在assert(newcom.GetKeyboard()-> m_strModel != oldcom.GetKeyboard()-> m_strModel);处会出现错误。
会提示:
test: main.cpp:15: int main(): Assertion `newcom.GetKeyboard()->m_strModel != oldcom.Get
Keyboard()->m_strModel' failed.
这里有必要将一些assert的用法。
assert() 宏用法
注意:assert是宏,而不是函数。在C的assert.h 头文件中。 assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义: #include <assert.h> void assert( int expression ); assert的作用是先计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息, 然后通过调用 abort 来终止程序运行。- 构造函数、拷贝构造函数
- 拷贝构造函数,构造函数
- 拷贝构造函数--默认拷贝构造函数
- 构造、拷贝构造函数基础
- 拷贝构造函数 深拷贝 浅拷贝
- 拷贝构造函数(深拷贝,浅拷贝)
- 拷贝构造函数浅拷贝深拷贝
- 拷贝构造函数,浅拷贝,深拷贝
- 拷贝构造函数 深拷贝 浅拷贝
- 拷贝构造函数----深拷贝、浅拷贝
- 拷贝构造函数
- 拷贝构造函数
- 浅析拷贝构造函数
- 拷贝构造函数
- 拷贝构造函数
- C++拷贝构造函数
- C++拷贝构造函数
- 拷贝构造函数
- 简易练习
- poj1548 - Robots
- 一个关于将满足给定条件的数据按顺序写到另一文件中的C语言函数。
- Android系统启动过程
- ArrayList和Hashtable的有关内容
- 拷贝构造函数
- S3C2440上触摸屏驱动实例开发讲解
- ActionScript中的vector和array
- 欧拉函数+容斥
- Enterprise Architect 使用笔记
- Scrum实践二——Daily Standup Meeting
- 系统结构
- android中各个部件驱动在源码中的位置
- Eclipse + JDK1.7 + Android SDK4.1 + ADT