0
点赞
收藏
分享

微信扫一扫

C++中运算符(加号、减号、左移、递增、赋值、关系、函数调用)重载实例


#include <iostream>
#include <string>

using namespace std;

class Persion
{
friend ostream& operator<<(ostream& out, Persion& p);
public:
Persion()
{

}
~Persion()
{
if (c)
{
delete c;
}
}
Persion(int a, int b)
{
this->a = a;
this->b = b;
}
Persion(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = new int(c);
}
//加号运算符重载
Persion operator+(const Persion p1)
{
Persion temp;
temp.a = this->a + p1.a;
temp.b = this->b + p1.b;
return temp;
}
Persion operator+(const int p1)
{
Persion temp;
temp.a = this->a + p1;
temp.b = this->b + p1;
return temp;
}
// 减号运算符重载
Persion operator-(const Persion p1)
{
Persion temp;
temp.a = this->a - p1.a;
temp.b = this->b - p1.b;
return temp;
}
//前置递增运算符重载
Persion& operator++()
{
this->a += 1;
this->b += 1;
return *this;
}
//后置递增运算符重载
Persion operator++(int)
{
Persion temp;
temp.a = this->a;
temp.b = this->b;

this->a += 1;
this->b += 1;
return temp;
}
//赋值运算符重载(解决深浅拷贝问题)
Persion& operator=(Persion& p)
{
this->a = p.a;
this->b = p.b;
if (this->c != NULL)
{
delete c;
this->c = NULL;
}
this->c = new int(*p.c);
return *this;
}
//关系运算符重载
bool operator==(Persion &p)
{
if (this->a == p.a && this->b == p.b)
{
return true;
}

return false;
}
bool operator!=(Persion& p)
{
if (this->a == p.a && this->b == p.b)
{
return false;
}

return true;
}
//函数调用运算符重载(仿函数)
void operator()()
{
cout << "a=" << this->a << " b=" << this->b<<endl;
}
int operator()(int num)
{
return this->a + num;
}

int a;
int b;
int* c;
};
//左移运算符重载
ostream& operator<<(ostream &out,Persion &p)
{
out << "a=" << p.a << " b=" << p.b;
return out;
}


int main()
{
Persion p1(1, 1);
Persion p2(2, 2);

//加号运算符重载测试
Persion p3 = p1+p2;
cout <<"加号运算符重载测试:" << p3.a << endl;

Persion p4 = p1 + 10;
cout << "加号运算符重载测试:" << p4.a << endl;

//减号运算符重载测试
Persion p5 = p1 - p2;
cout << "减号运算符重载测试:" << p5.a << endl;

//左移运算符重载测试
cout << "左移运算符重载测试:" << p5<< endl;

//前置递增运算符重载测试
Persion p6 = ++p5;
cout << "前置递增运算符重载测试:" << p6 << endl;

//后置递增运算符重载测试
Persion p7 = (p5 ++)++;
cout << "后置递增运算符重载测试:" << p7 << endl;

//赋值运算符重载测试
Persion p8( 8, 8, 8 );
Persion p9;
p9 = p8;
cout << "赋值运算符重载测试:" << p8 << endl;
cout << "赋值运算符重载测试:" << p9 << endl;

//关系运算符重载测试
cout << "关系运算符重载测试:" << (p9 == p8)<< endl;
cout << "关系运算符重载测试:" << (p9 != p8) << endl;

//函数调用运算符重载测试
Persion p10;
p10();
cout << "函数调用运算符重载测试:" << p10 (20) << endl;

return 0;
}

C++中运算符(加号、减号、左移、递增、赋值、关系、函数调用)重载实例_数据结构


举报

相关推荐

0 条评论