#include"iostream"
#include"string.h"
using namespace std;
class s{
private:
char *str;
public:
s():str(new char[1]){str[0]=0;}//构造函数让str指向null
const char*c_str(){return str;}
s & operator = (const char * x);//“=”重载(只能成员函数)
~s(){delete [] str;}//析构函数
};
s &s::operator = (const char * x){
delete [] str;
str = new char[strlen(x)+1];
strcpy(str,x);
return *this;//this指针
}
int main(){
s m;
m="i like you";
cout<<m.c_str()<<endl;
//s n="hello world"; 错误
s n;
n="syr";
cout<<n.c_str()<<endl;
}
赋值运算符的重载
最新推荐文章于 2024-01-22 21:32:52 发布