首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新人请问有关复制构造函数和赋值=重载的一段代码2个有关问题

2012-02-12 
新人请教有关复制构造函数和赋值重载的一段代码2个问题代码和问题如下:#includeiostream#includefstre

新人请教有关复制构造函数和赋值=重载的一段代码2个问题
代码和问题如下:
#include   <iostream>
#include   <fstream>
#include   <string>
using   namespace   std;


class   Base
{
public:
Base()
{
d=100;
}
~Base()
{
}
Base(const   Base&   A)//这个函数究竟应该怎么写(1)
{
//*this=A;//这样写可以么
}
const   Base   &   operator   =(   const   Base&   A)
{
(this-> d)=A.getD();//这句话编译不通过什么原因(2)
return   *this;
}
int   getD()
{
return   d;
}
void   test()
{
cout < <d < <endl;
cout < < "Can   this   sentence   be   output? " < <endl;
}

private:
int   d;
};


[解决办法]
Base(const Base& A)
{
d = A.d;
}
const Base & operator=(const Base& A)
{
d = A.d;
return *this;
}
直接这样不就可以了么?

(this-> d)=A.getD();这句有问题的原因是,常对象A调用了非常函数。因为常对象的数据成员在生存期内都是不可变的,所以常对象不能调用非常函数
[解决办法]

使用const关键字进行说明的成员函数,称为常成员函数。只有常成员函数才有资格操作常量或常对象,没有使用const关键字说明的成员函数不能用来操作常对象。常成员函数说明格式如下:

   <类型说明符> <函数名> ( <参数表> ) const;

其中,const是加在函数说明后面的类型修饰符,它是函数类型的一个组成部分,因此,在函数实现部分也要带const关键字。

热点排行
Bad Request.