对于左右可交换的重载操作符,一般不放在类中,而是作为friend的方式放在类外,可以和类一起丢在名字空间里面。
//Head.h
#pragma once
#ifndef HEAD_H
#define HEAD_H
class Foo {
friend int operator+(const Foo&left, const Foo&right);
private:
int n;
public:
Foo(int i):n(i){}
};
int operator+(const Foo&left, const Foo&right) {
return left.n + right.n;
}
#endif
由于隐式转换,可以任意和int类型的互相加。
#include"Head.h"
#include<iostream>
using std::cout;
using std::endl;
using std::ends;
int main()
{
Foo a(4),b(5);
cout << a + b << endl << a + 2 << endl << 3 + b;
}
//这两天同事忙着打麻将,无事可干的我想起几天前小胖的代码,便自我Mark下吧,加强下记忆
Zr
2020-01-07
于西岭雪山归来