64,685
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Base
{
private:
int * pBValue;
public:
Base()
{
pBValue = NULL;
}
Base(const int B_M_temp)
{
pBValue = new int;
*pBValue = B_M_temp;
}
Base(const Base &aa)
{
pBValue = new int;
*pBValue = *(aa.pBValue);
}
Base & operator= (const Base &B_M_temp)
{
if (this == &B_M_temp)
{
return *this;
}
pBValue = new int;
*pBValue = *(B_M_temp.pBValue);
return *this;
}
void set(const int B_M_temp)
{
*pBValue = B_M_temp;
}
void B_show() const
{
if (pBValue != NULL)
cout << "Base: " << *pBValue << endl;
else
cout << "空指针" << endl;
}
~Base()
{
delete pBValue;
}
};
class DeriveBase: public Base
{
private:
int * DB_pValue;
public:
DeriveBase()
{
DB_pValue = new int;
*DB_pValue = 0;
}
DeriveBase(const int DB_M_temp, const int DB_M_temp1):Base(DB_M_temp1)
{
DB_pValue = new int;
*DB_pValue = DB_M_temp;
}
DeriveBase(const DeriveBase &DB_M_temp):Base(DB_M_temp)
{
DB_pValue = new int;
*DB_pValue = *(DB_M_temp.DB_pValue);
}
DeriveBase & operator= (const DeriveBase &DB_M_temp)
{
if (this == &DB_M_temp)
{
return *this;
}
DB_pValue = new int;
*DB_pValue = *(DB_M_temp.DB_pValue);
return *this;
}
void DB_show() const
{
cout << "DeriveBase: " << *DB_pValue << endl;
B_show();
}
~DeriveBase()
{
delete DB_pValue;
}
};
int main()
{
//定义一个基类 base 并初始化
//输出基类
Base base(8254);
base.B_show();
cout << endl;
//定义一个基类 base1 并初始化
//输出基类
Base base1(base);
base1.B_show();
cout << endl;
//定义一个基类 base2
//给基类赋值一个值
//复制一个基类对象到另一个基类对象
//输出基类
Base base2;
base.set(123456789);
base2 = base;
base2.B_show();
cout << endl;
//定义一个派生类 dbase 并初始化
//输出派生类
DeriveBase dbase(100,2000);
dbase.DB_show();
cout << endl;
//定义一个派生类 dbase 并初始化
//输出派生类
DeriveBase dbase1(dbase);
dbase1.DB_show();
cout << endl;
//定义一个派生类 dbase 并初始化
//复制一个派生类对象到另一个派生类对象
//输出派生类
DeriveBase dbase2;
dbase2 = dbase1;
dbase.DB_show();
cout << endl;
base2 = dbase2; //这里使用派生类赋值给基类
base2.B_show();
cout << endl;
return 0;
}
base2 = dbase2; //这里使用派生类赋值给基类
base2.B_show();
cout << endl;