c++使用友元重载运算符

1. 前言

我感觉使用友元重载运算符,除了<<可以拼接cout以外,平时更多的可能是为了方便用户?

2. 代码

假如我现在有一个类,有xy2个数据成员,想实现对类的乘法,内部逻辑是对xy都做乘法。那么对于用户来讲,他是不是想既可以写 A = A ∗ 1.5 A=A*1.5 A=A1.5,又可以写 A = 1.5 ∗ A A=1.5*A A=1.5A这种?所以就用的上友元了。

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。
按任意键关闭此窗口. . .
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值