[问题] 用operator=()改以friend来撰写

楼主: j19920816 (Kaung)   2016-07-03 16:02:28
开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
DEV C++
错误结果(Wrong Output):
编译器出现"void operator=(CWin&, CWin&)' must be a nonstatic member function"
的错误
程式码(Code):(请善用置底文网页, 记得排版)
#include<iostream>
#include<cstdlib>
using namespace std;
class CWin
{
private:
char id,*title;
public:
CWin(char i='D',char *text="Default window"):id(i)
{
title=new char[50];
strcpy(title,text);
}
void set_data(char i,char *text)
{
id=i;
strcpy(title,text);
}
void show()
{
cout<<"Window "<<id<<": "<<title<<endl;
}
~CWin()
{
delete [] title;
}
CWin(const CWin &win)
{
id=win.id;
strcpy(title,win.title);
}
friend void operator=(CWin &win1,CWin &win2);//在类别里宣告
};
void operator=(CWin &win1,CWin &win2)///类别外面定义
{
win1.id=win2.id;
strcpy(win1.title,win2.title);
}
int main()
{
CWin win1('A',"Main window");
CWin win2;
win1.show();
win2.show();
operator=(win1,win2);
cout<<endl<<"设定 win1=win2之后..."<<endl;
win1.show();
win2.show();
win1.set_data('B',"hello window");
cout<<endl<<"更改win1的资料成员后..."<<endl;
win1.show();
win2.show();
system("pause");
return 0;
}
请问一下是哪边出现了问题@@?? 谢谢大家
作者: LiloHuang (十年一刻)   2016-07-03 16:25:00
根据 C++ 标准 13.5.3 描述,operator= 一定得是成员就像编译器跟你描述的错误一样,没有两个参数的版本也许可以看一下书本是用什么编译器,使其可以编译通过
作者: bibo9901 (function(){})()   2016-07-03 17:27:00
即使可以, 回传 void 也怪怪的
作者: jerryh001   2016-07-03 18:04:00
我们这边也教用void 是有什么优点吗
作者: b0920075 (Void)   2016-07-03 19:30:00
我们教的不是回传void
作者: tyc5116 (累人啊....)   2016-07-03 19:34:00
这是单纯测试吗?不然用这样的方式写operator感觉怪怪的
作者: schizophrena (你很記者你很腦殘)   2016-07-03 19:35:00
为什么operator可以在class外?这样不就不知道是哪个class会走这个operator?
作者: tyc5116 (累人啊....)   2016-07-03 19:42:00
operator可以在class外阿
作者: LiloHuang (十年一刻)   2016-07-03 20:06:00
Binary operator 可以摆外面,由参数型别决定谁走进来Copy assignment operator 则是得写成非静态成员函数通常会回传自己的参考 (i.e. return *this);来达成 assignment chaining (i.e. a = b = c;)回传用 void 就会阻碍 assignment chaining 的写法
楼主: j19920816 (Kaung)   2016-07-05 14:19:00
所以这题不能用friend了吗?@@
作者: LiloHuang (十年一刻)   2016-07-06 01:00:00
我认为不能用两个参数的版本,除非编译器有特异功能 XD

Links booklink

Contact Us: admin [ a t ] ucptt.com