《悬赏》困扰了小弟我很久的 重载赋值操作符的一个有关问题
《悬赏》困扰了我很久的 重载赋值操作符的一个问题!

问题是:图中红线的语句的 意义
先谢着了!
------解决方案--------------------
一个派生类中包含继承自基类的部分 和 自己特有的部分,所以当进行赋值运算时,不仅要将派生类特有的数据成员赋值给左侧对象,还要将继承自基类的部分也赋值给左侧对象。派生类自己特有的部分赋值在operator=函数里实现,而派生类中的基类部分通过调用基类的operator=函数进行赋值。
------解决方案--------------------
------解决方案--------------------
楼 上 正 解
我也写了一个例子说明这个问题:
程序执行结果为:
问题是:图中红线的语句的 意义
先谢着了!
------解决方案--------------------
一个派生类中包含继承自基类的部分 和 自己特有的部分,所以当进行赋值运算时,不仅要将派生类特有的数据成员赋值给左侧对象,还要将继承自基类的部分也赋值给左侧对象。派生类自己特有的部分赋值在operator=函数里实现,而派生类中的基类部分通过调用基类的operator=函数进行赋值。
------解决方案--------------------
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;
}
------解决方案--------------------
楼 上 正 解
我也写了一个例子说明这个问题:
// 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;
}
程序执行结果为: