转载:
https://www.cnblogs.com/ne-liqian/p/7905754.html
结构体中运算符的重载
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
struct point
{
int elem;
bool operator==(const point b) const
{
return this->elem == b.elem;
}
bool operator!=(const point b) const
{
return this->elem != b.elem;
}
bool operator<=(const point b) const
{
return this->elem <= b.elem;
}
bool operator<(const point b) const
{
return this->elem < b.elem;
}
bool operator>=(const point b) const
{
return this->elem >= b.elem;
}
bool operator>(const point b) const
{
return this->elem > b.elem;
}
}a[10002],now;
int main()
{
bool flag;
int i, n, k;
scanf("%d", &n);
for (i = 0; i <= n - 1; i++)
{
scanf("%d", &a[i].elem);
}
scanf("%d", &k);
for (i = 0; i <= k - 1; i++)
{
scanf("%d", &now.elem);
flag = binary_search(a, a + n , now);
if (flag == true)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}
常见代码:
重载+
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class ca
{
public:
int value;
//重载为成员函数格式
int operator+(const ca &v){
return this->value + v.value; // 等同于return value+v.value;
}
};
//重载为非成员函数格式
int operator+(const ca &v1, const ca &v2)
{
return v1.value + v2.value;
}
int main()
{
ca a, b;
a.value = 10;
b.value = 20;
printf("a+b:%d\n", a + b); // 优先用成员函数
return 0;
}
重载<<:
转载:
#include <iostream>
#include <iomanip>
using namespace std;
class Complex
{
private:
double m_a, m_b;
public:
//以全局函数的形式进行重载
friend Complex operator+(const Complex &a, const Complex &b);
//以全局函数重载>> 和 <<
friend istream & operator >> (istream & in, Complex & a);
friend ostream & operator << (ostream & out, const Complex & b);
void show()
{
cout << this->m_a << " " << this->m_b << endl;
}
public:
Complex(double a, double b) : m_a(a),m_b(b){}
Complex(){}
};
Complex operator+(const Complex &a, const Complex &b)
{
return Complex(a.m_a+b.m_a, a.m_b + b.m_b);
}
istream & operator >> (istream & in, Complex & a)
{
in >> a.m_a >> a.m_b;
return in; // 返回 istream ,方便连续使用
}
ostream & operator << (ostream &out, const Complex &b)
{
out << b.m_a << " " << b.m_b;
return out;
}
int main()
{
Complex a,b,c;
cin >> a >> b;
c = a + b;
cout << c << endl;
return 0;
}
重载++:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
// 例如这里的重载递增就是为了增加pos的值
class ca
{
public:
int pos;
//前置递增就是增加当前对象的pos的值,并且返回当前对象
ca operator++(){
pos++;
return *this;
}
//后置递增就是增加当前对象的pos的值,并且返回增加pos之前的该对象
ca operator++(int){
ca ret = *this;
++*this; //这个会调用上面的函数,其实这里可以换成pos++;
return ret;
}
};
int main()
{
ca a, b;
a.pos = 1;
b = a++;
cout << "b1:" << b.pos << endl; // b1:1
b = ++a;
cout << "b2:" << b.pos << endl; // b1:3
return 0;
}