/*************************************************************************
> File Name: class.cpp
> Author: gaopeng QQ:22389860 all right reserved
> Mail: gaopp_200217@163.com
> Created Time: Sat 25 Mar 2017 04:40:31 PM CST
************************************************************************/
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
class testop
{
private:
char* mystr;
int len;
public:
testop(const char* instr)
{
this->len = strlen(instr)+1;
this->mystr = new char[this->len];
memset(this->mystr,0,this->len);
strcpy(this->mystr,instr);
}
testop()
{
this->len = 0;
this->mystr = NULL;
}
testop(const testop& b)//copy 构造函数深拷贝
{
this->len = b.len;
this->mystr = new char[b.len];
memset(this->mystr,0,this->len);
strcpy(this->mystr,b.mystr);
}
void printmystr()
{
cout<<this->mystr<<endl;
}
~testop()
{
delete [] this->mystr;
}
//操作符重载 + 使用成员函数
testop operator+(const testop& b)
{
testop temp;
temp.len = this->len + b.len;
temp.mystr = new char[temp.len];
memset(temp.mystr,0,temp.len);
strcat(strcat(temp.mystr,this->mystr),b.mystr);
return temp;
}
//操作符重载 = 使用成员函数 深拷贝
testop& operator=(const testop& b)
{
if(this->mystr != NULL)//必须先释放内存
{
delete [] this->mystr;
}
this->len = b.len;
this->mystr = new char[this->len];
memset(this->mystr,0,this->len);
strcpy(this->mystr,b.mystr);
return *this;
}
//操作符重载前置(++),使用成员函数 支持链试编程
testop& operator++()
{
this->len = this->len+this->len;
char* temp = new char[this->len];
memset(temp,0,this->len);
strcat(strcat(temp,this->mystr),this->mystr);
delete [] this->mystr;
this->mystr = new char[this->len];
strcpy(this->mystr,temp);
delete [] temp;
return *this;
}
//操作符重载后置(++),使用成员函数 不支持链试编程 因为返回的为一个匿名对象
testop operator++(int)
{
testop tempop = *this;
this->len = this->len+this->len;
char* temp = new char[this->len];
memset(temp,0,this->len);
strcat(strcat(temp,this->mystr),this->mystr);
delete [] this->mystr;
this->mystr = new char[this->len];
strcpy(this->mystr,temp);
delete [] temp;
return tempop;
}
//操作符重载 << 必须使用友元函数 支持链试编程
friend ostream& operator<<(ostream& out,testop& b);
//操作符重载 == 使用成员函数
bool operator==(testop& b)
{
if(this->len == b.len && !strcmp(this->mystr,b.mystr))
{
return true;
}
else
{
return false;
}
}
//操作符重载 != 使用成员函数
bool operator!=(testop& b)
{
if((*this) == b )
{
return false;
}
else
{
return true;
}
}
};
ostream& operator<<(ostream& out,testop& b) // 友元函数
{
out<<b.mystr;
return out;
}
int main()
{
testop c("ab");
cout<<c<<endl;
c++;
++c;
cout<<"c:"<<c<<endl;
testop a=c;
cout<<"a:"<<a<<endl;
if(a == c)
{
cout<<"相等"<<endl;
}
a = c+a;
cout<<"a=c+a:"<<a<<endl;
if(a !=c )
{
cout<<"不相等"<<endl;
}
}
感谢你能够认真阅读完这篇文章,希望小编分享的“C++如何实现操作符重载”这篇文章对大家有帮助,同时也希望大家多多支持天达云,关注天达云行业资讯频道,更多相关知识等着你来学习!