/*
使用非成员函数重载运算符
非成员函数无法访问私有变量,所以将非成员函数设置为友元(违反了oop数据隐藏原则?)
使用友元的方法:
1.在类中声明友元,带friend关键字
2.友元函数定义,无需带friend关键字
友元的几种类型:
1.友元函数
2.友元类
3.友元成员函数
成员函数重载只能用对象系数,而不能用系数对象的写法,所以出现了友元函数
friend Trust operator*(int x,Trust & t);
乍一看,可能觉得友元函数违反了oop数据隐藏原则
答:观点太片面了。出现友元函数这个使用场景是为了解决 对象系数 或者 系数对象不能同时使用的问题,系数在前或在
后都不会影响计算结果的。前一个要求有类成员函数,后一个要求有友元函数,这是c++句法的结果,而不是概念上的差别。
通过友元函数和类方法可以让接口同时支持这两种操作。
另外,只有类声明才可以指定谁是友元函数,因此类声明仍然可以控制哪些函数可以访问私有数据。
总之,类成员方法和友元函数只是表达类接口的不同机制。
优化:将友元函数写成非友元函数
Trust operator*(int x,Trust & t) {
return t * x;//倒序
}
然后去掉类中的声明
*/
#include <iostream>
#include <string>
using namespace std;
class Trust {
private:
int x;
int y;
public:
Trust(){}
Trust(int x,int y){
this->x = x;
this->y = y;
}
void set(int x,int y){
this->x = x;
this->y = y;
}
void print(){
cout << x << " " << y << endl;
}
//成员函数重载只能用对象*系数,而不能用系数*对象的写法,所以出现了友元函数
Trust operator*(int x) const {
Trust temp;
temp.x = this->x * x;
temp.y = this->y * x;
return temp;
}
friend Trust operator*(int x,Trust & t);
};
//可以使用系数*对象的写法
Trust operator*(int x,Trust & t) {
Trust temp;
temp.x = t.x * x;
temp.y = t.y * x;
return temp;
}
int main()
{
Trust a(1,2);
Trust b(1,1);
Trust c = 2*a;
c.print();
c = a*2;
c.print();
}