1. 前言
我感觉使用友元重载运算符,除了<<
可以拼接cout
以外,平时更多的可能是为了方便用户?
2. 代码
假如我现在有一个类,有x
和y
2个数据成员,想实现对类的乘法,内部逻辑是对x
和y
都做乘法。那么对于用户来讲,他是不是想既可以写
A
=
A
∗
1.5
A=A*1.5
A=A∗1.5,又可以写
A
=
1.5
∗
A
A=1.5*A
A=1.5∗A这种?所以就用的上友元了。
2.1 未使用友元,只实现成员函数
2.1.1 MyClass.h
#pragma once
#include<iostream>
class MyClass
{
private:
double x;
double y;
public:
// 构造函数
MyClass(int a,int b):x(a),y(b){}
void print() { std::cout << x << ", " << y << std::endl; }
// 成员函数
MyClass operator*(const double coef); //A*c 即 this->operator*(coef)
};
2.1.2 MyClass.cpp
#include "MyClass.h"
MyClass MyClass::operator*(const double coef)
{
this->x *= coef;
this->y *= coef;
return *this;
}
2.1.3 main.cpp
#include<iostream>
#include"MyClass.h"
using namespace std;
int main()
{
MyClass my_obj(1,2);
// 打印初始值
my_obj.print();
// 执行乘法
my_obj = my_obj * 1.5;
// 打印乘法之后的值
my_obj.print();
// 使用double在前面的方式
my_obj = 1.5 * my_obj; // 注意这句代码是报错的
return 0;
}
2.2 使用友元後
2.2.1 MyClass.h
#pragma once
#include<iostream>
class MyClass
{
private:
double x;
double y;
public:
// 构造函数
MyClass(int a,int b):x(a),y(b){}
void print() { std::cout << x << ", " << y << std::endl; }
// 成员函数
MyClass operator*(const double coef); //A*c 即 this->operator*(coef)
// 友元函数
friend MyClass operator*(const double coef, MyClass& obj1);
};
2.2.2 MyClass.cpp
#include "MyClass.h"
MyClass MyClass::operator*(const double coef)
{
this->x *= coef;
this->y *= coef;
return *this;
}
MyClass operator*(const double coef, MyClass& obj1)
{
return obj1.operator*(coef);
}
2.2.3 main.cpp
#include<iostream>
#include"MyClass.h"
using namespace std;
int main()
{
MyClass my_obj(1,2);
// 打印初始值
cout << "原始值: ";
my_obj.print();
// 执行乘法
my_obj = my_obj * 1.5;
// 打印乘法之后的值
cout << "使用成员函数乘法之后的值: ";
my_obj.print();
// 使用double在前面的方式
cout << "使用友元函数乘法之后的值: ";
my_obj = 2 * my_obj; // 注意这句代码是报错的
// 再次打印乘法之后的值
my_obj.print();
return 0;
}
2.2.4 结果
原始值: 1, 2
使用成员函数乘法之后的值: 1.5, 3
使用友元函数乘法之后的值: 3, 6
E:\projectFiles\CPPcodes\learn_cpp\friend_test\x64\Release\friend_test.exe (进程 28448)已退出,代码为 0。
按任意键关闭此窗口. . .