0
点赞
收藏
分享

微信扫一扫

C++ 运算符重载


技术,是实现目标的手段,重载运算符,可以让程序看起来更优美,更优美的程序更具有可读性,如果不重载,使用函数一样可以达到目的,但那样子程序看起来很蹩脚,直接上代码


      

#include<iostream>
using namespace std;
class Demo
{
private:
int index;
public:
Demo(int i)
{
index = i;
}

int GetIndex(){return index;}

// 重载小于操作
bool operator <(const Demo& d)
{
if(this->index<d.index)
{
return true;
}
return false;
}

// 重载 +
const Demo operator +(const Demo& d)
{
int sum = index + d.index;
return Demo(sum); // 注意,这里一定要返回一个新对象
}

// 重载 >

bool operator >(const Demo& d)
{
if(this->index>d.index)
{
return true;
}

return false;
}

// 重载 *

const Demo operator *(const Demo& d)
{
int multiply = index*d.index;
return Demo(multiply); //返回新对象
}

// 重载 ++ ++a
Demo operator ++()
{
index++;
return *this;
}

// a++
const Demo operator++(int x)
{
Demo tmp = *this;
this->index++; // 虽然执行了++操作,但是tmp里的值仍然是加1之前的值
return tmp;
}

};


测试代码

#include"Demo.h"
int main()
{

Demo d1(3);
Demo d2(5);
if(d1<d2)
{
cout<<"小于"<<endl;
}

d1 = d1 + d2;
if(d1>d2)
{
cout<<"大于"<<endl;
}

d1 = d1*d2;
cout<<d1.GetIndex()<<endl;

d1++;
cout<<d1.GetIndex()<<endl;
++d1;
cout<<d1.GetIndex()<<endl;

return 1;
}



举报

相关推荐

0 条评论