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();
}
现写了操作符重载示例,如下:
//在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();
}
相关文章推荐
- C++重载操作符与转换
- C++高精度运算类bign (重载操作符)
- [C/C++] 第14章 重载操作符与转换 《C++ Primer》
- C++中operator关键字(重载操作符)
- C++第十八天 重载操作符
- C++重载操作符于转换 笔记
- C++重载操作符的简单实例
- STL运用的C++技术(5)——重载操作符
- c++中重载操作符表,可以帮助重载哪些操作符,以及到底是重载为类方法还是类的友元方法
- C++智能指针与重载操作符
- 【C++重载操作符】operator double () const {}的理解
- c++重载操作符续
- c++之---初探重载操作符
- C++重载操作符和转换
- c++重载操作符
- C++重载操作符
- C++学习笔记41——重载操作符之下标操作符
- c++重载操作符的使用及实现编译多态
- C++ 自定义比较:仿函数、函数与重载操作符
- 漫漫编程路——C++篇(七)——关于重载操作符(二)(修改)