为解决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();
- }