//修改上例,采用赋值操作符的方式初始化对象
#include<iostream.h>
#include<string.h>
class string
{
private:
char * str;
public:
string(char * s=" ")
{
cout << "在构造函数中/n";
int size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
string& operator=(string & ss)//赋值操作符方式
{
cout << "赋值操作符/n";
delete str;
str=new char[strlen(ss.str)+1];
strcpy(str,ss.str);
return *this;
}
~string()
{delete str;}
void showstring()
{cout << str << endl;}
};
void main()
{
string s1="内存中得字符串";
cout << "s1 = ";
s1.showstring();
string s2;
s2=s1;
cout << "s2 = ";
s2.showstring();
}
#include<iostream.h>
#include<string.h>
class string
{
private:
char * str;
public:
string(char * s=" ")
{
cout << "在构造函数中/n";
int size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
string& operator=(string & ss)//赋值操作符方式
{
cout << "赋值操作符/n";
delete str;
str=new char[strlen(ss.str)+1];
strcpy(str,ss.str);
return *this;
}
~string()
{delete str;}
void showstring()
{cout << str << endl;}
};
void main()
{
string s1="内存中得字符串";
cout << "s1 = ";
s1.showstring();
string s2;
s2=s1;
cout << "s2 = ";
s2.showstring();
}