64,637
社区成员
发帖
与我相关
我的任务
分享
m_with = rhs.m_with;
m_height = rhs.m_height;
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string.h>
#include <iostream.h>
class CBase
{
public:
CBase(int i)
{
cout<<"Constructing CBase!"<<endl;
idata_base=i;
cout<<"idata_base: "<<idata_base<<endl;
}
~CBase()
{
cout<<"Destructing CBase!"<<endl;
}
int idata_base;
virtual void GetValue(char *pName);
CBase& operator=(const CBase& bas);
};
class CDerived:public CBase
{
public:
CDerived(int i):CBase(i)
{
cout<<"Constructing CDerived!"<<endl;
idata_derived=i;
cout<<"idata_derived: "<<idata_derived<<endl;
}
~CDerived()
{
cout<<"Destructing CDerived!"<<endl;
}
int idata_derived;
void GetValue(char *pName);
CDerived& operator=(const CDerived& de);
};
CBase& CBase::operator=(const CBase& ba)
{
this->idata_base=ba.idata_base;
return *this;
}
void CBase::GetValue(char *pName)
{
if(!strcmp("CBase",pName))
{
cout<<"idata_base: "<<idata_base<<endl;
return;
}
else
return;
}
CDerived& CDerived::operator=(const CDerived& de)
{
CBase::operator=(de);
this->idata_derived=de.idata_derived;
return *this;
}
void CDerived::GetValue(char *pName)
{
if(!strcmp("CDerived",pName))
{
cout<<"idata_base: "<<idata_base<<endl;
cout<<"idata_derived: "<<idata_derived<<endl;
return;
}
else
return;
}
int main(int argc, char* argv[])
{
CBase *pBase;
CDerived *pDerived;
pBase=new CBase(12);
pBase->GetValue("CBase");
pDerived=new CDerived(34);
CDerived tmpDerived(56);
cout<<"Before: "<<endl;
tmpDerived.GetValue("CDerived");
tmpDerived=*pDerived;
cout<<"After: "<<endl;
tmpDerived.GetValue("CDerived");
delete pDerived;
delete pBase;
return 0;
}
class Base { /*...*/ }; // 基类
class D : public Base { // D类派生自Base类
public:
D& operator=(const D& rhs); // 赋值函数
};
D& D::operator=(const D& rhs)
{
Base::operator=(rhs); // 为基类部分赋值
// 为派生类自己的成员部分赋值
// ...
return *this;
}