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<
}
加“”
class c{
friend c& operator+( c&, c&); // operator+只有一个参数
public:char d[27];
c(){}
};
c& operator+( c& a, c& b) //不应该返回一个局部变量的引用,因为局部变量载函数返回时,会被自动析构。此时返回值变成了一个空对象的引用。
{
int n1=strlen(a.d),n2=strlen(b.d);
c temp;
strcpy(temp.d,a.d);
strcat(temp.d,b.d);
return temp;
}
int main(){
c z,x;
z.d="wwwwww"; //非法的赋值,不能将const char * 给字符数组,要用strcpy()
x.d="aaaaaa";
z=z+x; //有歧义的operator+
cout<
}
正确的如下:
#include
#include
class c{
public:char d[27];
c operator+(c& a);
c(){}
};
c c::operator+( c& a)
{
int n1=strlen(this->d),n2=strlen(a.d);
c temp;
strcpy(temp.d,this->d);
strcat(temp.d,a.d);
return temp;
}
int main(){
c z,x;
strcpy( z.d, "wwwwww");
strcpy( x.d, "aaaaaa");
z=z+x;
cout<
}
程序修改如下:
#include
#include
class c{
public:
c operator + (c a);
public:char d[27];
c(){}
};
c c::operator +(c a)
{
int n1=strlen(a.d);
c temp;
strcpy(temp.d,d);
strcat(temp.d,a.d);
return temp;
}
int main(){
c z,x;
strcpy(z.d,"wwwwww");
strcpy(x.d,"aaaaaa");
z=z+x;
cout<
}
#include
#include
class c{
friend c& operator+( c&, c&);
public:char d[27];
c(){}
};
c& operator+( c& a, c& b)
{
int n1=strlen(a.d),n2=strlen(b.d);
c temp;
strcpy(temp.d,a.d);
strcat(temp.d,b.d);
//return temp; //这里返回局部变量也有问题,因为函数退出后,他就不存在了,应该返回a的。修改为下面两句:
a=temp;
return a;
//最好的写法是把这个函数写成下面这样:
//strcat(a.d,b.d);
//return a;
}
int main()
{
c z,x;
strcpy(x.d,"wwwwww");//z.d="wwwwww";
strcpy(x.d,"aaaaaa");//x.d="aaaaaa"; //不能这样直接赋值,因为"aaaaaa"不是类对象,要用字符串拷贝函数strcpy完成
z=z+x;
cout<
}