c++ 派生类 复制构造函数、赋值函数 小例子

class Base

{

public:

Base(int n):num(n){}

Base(const Base& rhs):num (rhs.num){}

Base& operator = (const Base& rhs)

{

if (this != &rhs)

{

num = rhs.num;

}

return *this;

}

virtual ~Base(){}

virtual void print() { cout<<num<<endl; }

void print(int i) { cout<<i<<endl;}

int getnum(){ return num;}

private:

int num;

};

 

class Dervied:public Base

{

public:

Dervied(int n,const string & str):Base(n),name(str){}

Dervied(const Dervied& rhs):Base(rhs),name(rhs.name){}

Dervied& operator =(const Dervied& rhs) 

{

if (this != &rhs)

{

Base::operator =(rhs);

name = rhs.name;

}

return *this;

}

~Dervied(){}

void print(void) { cout<< name <<getnum() << endl;}

private:

string name;

};

 

 

void main( void )

{

Base      item(5);

Dervied   iDerv(2,"hi");

item.print();

iDerv.print();

cout<<"--------------------"<<endl;

Base* iter=new Dervied( 3,"hello");

iter->print(100);

}

你可能感兴趣的:(c++ 派生类 复制构造函数、赋值函数 小例子)