isiahe分析的比较透彻。不过也还是有些许问题。
一,对于isiahe给LZ的点评中,友元函数的重载是有两个参数,这点LZ是对的。
二,isiahe的正解无法实现连加,比如z=z+x+x;会出现问题。
返回一个局部变量的引用问题,不经常练习编程会常出现,通常的解决方法,个人心得:一是作为参数传递,如MSDN中定义的函数输出很多是通过这种方法。二是作为全局变量(一般不建议)。三是转变为传值调用。
#include
#include
class c{
friend c operator+( c&, c&);
public:
char d[27];
c(){}
};
c operator+( c& a, c& b)
{
c temp;
strcpy(temp.d,a.d);
strcat(temp.d,b.d);
return temp;
}
int main(){
c z,x;
strcpy(z.d,"wwwww");
strcpy(x.d,"aaaaaa");
z=z+x+x;
cout<
}
或者,以下MSDN中更常用,个人更喜欢。
#include
#include
class c{
friend c& operator+( c&, c&);
public:
char d[27];
c(){}
};
c& operator+( c& a, c& b)
{
strcat(a.d,b.d);
return a;
}
int main(){
c z,x;
strcpy(z.d,"wwwww");
strcpy(x.d,"aaaaaa");
z=z+x+x;
cout<
}