您的位置:首页 > 编程语言 > C语言/C++

C++重载操作符

2008-10-26 11:16 204 查看
为解决fan125849143在百度知道上的提问:http://zhidao.baidu.com/question/73152641.html

现写了操作符重载示例,如下:

//在vc6下编译通过

//修改:qmroom

//2008-10-25 23:15

//blog:http://blog.csdn.net/qmroom

//Email:qmroom#126.com #=@

#include <iostream.h>

#include <string.h>

#include <assert.h>

class com

{

private:

char *str;

public:

com() : str(NULL) {}

com(const com &c) : str(NULL)

{

*this = c; //或者 this->operator=(c);

}

com(const char *pstr) : str(NULL)

{

*this = pstr; //或者 this->operator=(pstr);

}

~com()

{

delete []str;

}

public:

com &operator=(const com &c1)

{

*this = c1.str; //或者 this->operator=(c1.str);

return *this;

}

com &operator=(const char *pstr)

{

if (str)

delete []str;

if (!pstr)

{

str = NULL;

return *this;

}

str=new char[strlen(pstr)+1];

assert(str!=NULL);

strcpy(str, pstr);

return *this;

}

com operator+(const com &c1) const

{

char *p=new char[strlen(str)+strlen(c1.str)+1];

assert(p!=NULL);

strcpy(p, str);

strcat(p, c1.str);

com myCom(p);

delete []p;

return myCom;

}

void print() const

{

cout<<str<<endl;

}

};

void main()

{

char *p1="aaa";

char *p2="bbb";

com a(p1),b(p2),c;

c=a+b;

c.print();

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