拷贝构造函数

来源:互联网 发布: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 来终止程序运行。