#include <iostream.h>
#include <string>
class mystring{
char * pstr;
int length;
public:
mystring(){
pstr=NULL;
length =0;}
mystring(char * p,int n){
pstr = new char[n];
pstr= strcpy(p,pstr);
}
~mystring(){delete[]pstr;}
mystring & operator = (const mystring & temp){
if(pstr!=NULL)
delete [] pstr;
length=temp.length;
pstr=new char[length+1];
strcpy(pstr,temp.pstr);
return *this;
}
friend ostream & operator<<(ostream & os,mystring & temp);
friend istream & operator>>(istream & is,mystring & temp);
};
ostream & operator<<(ostream & os,mystring & temp){
cout<<temp.pstr;
return os;
}
istream & operator>>(istream & is,mystring & temp){
char p[10000];
if((temp.pstr)!=NULL)
delete []temp.pstr;
cout<<"请输入字符串内容:"<<endl;
cin>>p;
temp.pstr=new char[strlen(p)+1];
strcpy(temp.pstr,p);
temp.length=strlen(p);
return is;
}
void main(){
mystring a,b;
cin>>a;
b=a;
cout<<"b="<<b<<endl;
}
有引用符不报错
没有引用符 报错了
不加也可以,但是你要正确实现拷贝构造函数。
加上&,直接传引用,不需要调用拷贝构造函数。
当程序没有显式地提供一个以本类或本类的引用为参数的赋值运算符重载函数时,编译器会自动提供一个。 前面加上&(引用)运算符进行连续操作时,这些运算符的返回值一定要是一个对象或者引用才行,不然就会出现错误(参数类型不符合)。返回引用的好处既可以避免拷贝构造函数和析构函数的调用。