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

percepto 2014-07-29 09:39:42


问题是:图中红线的语句的 意义


先谢着了!
...全文
178 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
adaq 2014-08-04
  • 打赏
  • 举报
回复
C++ 减小代码冗余的方法
adaq 2014-08-04
  • 打赏
  • 举报
回复
这句话等同于

m_with = rhs.m_with;
m_height = rhs.m_height;
勤奋的小游侠 2014-08-01
  • 打赏
  • 举报
回复
这是显式调用基类的operator = 函数,C++基础内容之一。 子类要赋值之前,肯定要先把父类赋值先。
lm_whales 2014-08-01
  • 打赏
  • 举报
回复
调用基类的operator = 复制基类子对象, 然后添加派生类自己定义的数据的复制代码,实现派生类的 operator =
caewow 2014-07-29
  • 打赏
  • 举报
回复
楼 上 正 解

我也写了一个例子说明这个问题:

// 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;
}

程序执行结果为:
神奕 2014-07-29
  • 打赏
  • 举报
回复

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; 
}
神奕 2014-07-29
  • 打赏
  • 举报
回复
一个派生类中包含继承自基类的部分 和 自己特有的部分,所以当进行赋值运算时,不仅要将派生类特有的数据成员赋值给左侧对象,还要将继承自基类的部分也赋值给左侧对象。派生类自己特有的部分赋值在operator=函数里实现,而派生类中的基类部分通过调用基类的operator=函数进行赋值。
taodm 2014-07-29
  • 打赏
  • 举报
回复
你的教材里真的没讲么?使用作用域限定::来调用函数,是个最基本语法啊。
percepto 2014-07-29
  • 打赏
  • 举报
回复
有没有人会,或者提示一下 都可以

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧