C++运算符重载:赋予运算符另一种作用,实现自定义类型的运算
如对象+对象变成int+int一样
C++运算符重载内容:
1.友元重载 /友元=》声明 友元关系是单向的,不可传递/
2.输入输出流重载
class CString
{
public:
CString(char *p = NULL){
if(p!= NULL)
{
_pstr=new char[strlen(p)+1];
strcpy(_pstr,p);
}
else
{
_pstr=new char[1];
*_pstr=0;
}
}
~CString()
{
delete []_pstr;
_pstr=NULL;
}
CString(const CString &src)
{
_pstr=new char[strlen(src._pstr)+1];
strcpy(_pstr,src._pstr);
}
CString& operator=(const CString &src)
{
if(*this == src)
{return *this;}
delete []_pstr;
_pstr=new char[strlen(src._pstr)+1];
strcpy(_pstr,src._pstr);
return *this;
}
bool operator>(const CString &src)const//对象之间>的重载
{
return strcmp(this->_pstr,src._pstr)>0;
}
bool operator<(const CString &src)const//对象之间<的重载
{
return strcmp(this->_pstr,src._pstr)<0;
}
bool operator==(const CString &src)const//对象之间=的重载
{
return strcmp(this->_pstr,src._pstr)==0;
}
int length()const
{
return strlen(this->_pstr)+1;
}
char operator[](int index)const//对象之间[]的重载
{
return this->_pstr[index];
}
const char* c_str()const
{
return this->_pstr;
}
private:
char *_pstr;
friend CString operator+(const CString &lhs, const CString &rhs);//友元声明
friend ostream& operator<<(ostream &out, const CString &str);//友元声明
};
CString operator+(const CString &lhs, const CString &rhs)//对于对象+对象的重载
{//这里并不能返回引用,原因:返回引用时,定义的临时对象并不能被析构,程序运行不
//下去;不加引用时,返回的对象会被保存一个临时对象返回回去;
char*tem=new char[strlen(lhs._pstr)+strlen(rhs._pstr)+2];
strcpy(tem,lhs._pstr);
strcat(tem,rhs._pstr);
CString tmp(tem);
delete []tem;
return tmp;
}
ostream& operator<<(ostream &out, const CString &str)//输出重载,cout的返回值类型是ostream
{
out<<str._pstr;
return out;
}
int main()
{
CString str1 = "aaa";
CString str2 = str1;
CString str3;
str3 = str1;
cout<<str1<<endl;
CString str4 = str1 + str3;
str4 = str1 + "bbb";
str4 = "ccc" + str1;
cout << str4 << endl;
if (str4 > str1)
{
cout << "str4 > str1" << endl;
}
else
{
cout << "str4 < str1" << endl;
}
int len = str4.length();
for (int i = 0; i < len; i++)
{
cout << str4[i]<<" ";
}
cout << endl;
char buf[1024] = { 0 };
strcpy(buf, str4.c_str());
cout << "buf:" << buf << endl;
return 0;
}