【发布时间】:2015-08-08 15:52:17
【问题描述】:
我想知道如何在这个连接过程中调用复制构造函数。 s3=s1+s2;应该能够调用复制构造函数并将其分配给 s3。甚至可能吗? 如果是,请在这里帮助我。谢谢
#include<iostream.h>
#include<conio.h>
#include<string.h>
class String
{
char x[40];
public:
String() { } // Default Constructor
String( char s[] )
{
strcpy(x,s);
}
String( String & s )
{
strcpy(x,s.x );
}
String operator + ( String s2 )
{
String res;
strcpy( res.x,x );
strcat( res.x,s2.x);
return(res);
}
friend ostream & operator << ( ostream & x,String & s );
};
ostream & operator << ( ostream & x,String & s )
{
x<<s.x;
return(x);
}
int main()
{
clrscr();
String s1="Vtu";
String s2="Belgaum";
String s3 = s1+ s2; // Should invoke copy constructor to concatenate and assign
cout<<"\n\ns1 = "<<s1;
cout<<"\n\ns2 = "<<s2;
cout<<"\n\ns1 + s2 = "<<s3;
getch();
return 0;
}
【问题讨论】:
-
s1=s2调用拷贝构造函数的方式,表达式String s3 = s1+s2;也应该能够调用复制构造函数。如果你知道怎么做,请帮忙。
标签: c++ string constructor copy concatenation