重载(一),复制构造函数

初始化对象

Cat(): 
itsAge(
5),
itsWeight(
8)
{ }

在初始化阶段初始化数据成员通常更清晰,效率更高。
有些数据成员必须初始化,不能在构造函数体内赋值。包括引用和常数。
只要有可能就应该使用初始化的语法。

复制构造函数(Copy Constructor)

复制构造函数的参数只有一个,即同一类的对象引用。通常应该是常数引用,因为构造函数不改变传递进来的对象。

CAT (const CAT& theCat);

默认的复制构造函数是浅复制。
如果对象中含有在堆中分配的成员变量,则默认的复制构造函数只会复制其指针,当一个副本被删除时,另一个副本的变量却仍然指向堆中的那块内存,这样可能会使程序崩溃。
因此,通常需要自己实现复制构造函数。(进行深复制)

#include <iostream>
using namespace std;

class CAT
{
public:
    CAT();
    CAT(
const CAT&); // copy constructor
    ~CAT();

    
int GetAge() const {return *itsAge;}
    
int GetWeight() const {return *itsWeight;}
    
void SetAge(int age) {*itsAge = age;}

private:
    
int* itsAge;
    
int* itsWeight;
}
;

CAT::CAT() 
{
    itsAge 
= new int;
    itsWeight 
= new int;
    
*itsAge = 5;
    
*itsWeight = 9;
}


// rhs 在 C++ 中常用来表示复制构造函数的参数。 rhs = 右端(right-hand side)
CAT::CAT(const CAT& rhs) {
    itsAge 
= new int;
    itsWeight 
= new int;
    
*itsAge = rhs.GetAge();
    
*itsWeight = rhs.GetWeight();
}


CAT::
~CAT() {
    delete itsAge;
    itsAge 
= 0;
    delete itsWeight;
    itsWeight 
= 0;
}


int main(int argc, char *argv[])
{
    CAT frisky;
    cout 
<< "frisky's age: " << frisky.GetAge() << endl;
    cout 
<< "Setting frisky to 6\n";
    frisky.SetAge(
6);
    cout 
<< "Creating boots from frisky\n";
    CAT boots(frisky);
    cout 
<< "frisky's age: " << frisky.GetAge() << endl;
    cout 
<< "boots' age: " << boots.GetAge() << endl;
    cout 
<< "Setting frisky to 7\n";
    frisky.SetAge(
7);
    cout 
<< "frisky's age: " << frisky.GetAge() << endl;
    cout 
<< "boots' age: " << boots.GetAge() << endl;
     
    
return 0;
}

posted on 2005-04-26 10:33  NeilChen  阅读(1278)  评论(0编辑  收藏  举报

导航