您的位置:首页 > 其它

拷贝构造函数,赋值运算符重载,友元输出重载

2013-09-16 14:01 232 查看
#include <iostream>
using namespace std;

class T{
public:
T():buf(NULL){}
T(char *s)
{
buf = new char[strlen(s) + 1];
strcpy(buf, s);
}
T(const T& t)
{
char* t_buf = t.buf;
buf = new char[strlen(t_buf) + 1];
strcpy(buf, t_buf);
}
T& operator=(const T& t)
{
if(this == &t)
return *this;
char* b = new char[strlen(t.buf) + 1];
strcpy(b, t.buf);
if(buf!=NULL)
delete buf;
buf = b;
}
~T()
{
if(buf!=NULL)
delete buf;
}
char* get_buf(){return buf;}
friend ostream& operator<<(ostream& os, const T& t)
{
os<<t.buf;
return os;
}
private:
char *buf;
};

int main()
{
T t("abcd");
cout<<t<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: