友元函数

1、运算符声明成类成员还是声明独立友元函数建议准则:
  1. C++规定,赋值运算符=、数组下标运算符[]、函数调用运算符、成员访问运算符->在重载时必须声明为类的成员函数
  2. 流运算符<<、>>、类型转换运算符不能定义类的成员函数,只能是友元函数
  3. 一元运算符和和赋值运算符重载时,一般声明类的成员函数
  4. 二元运算符在运算符重载时,一般声明为友元函数
2、问题引出
Test test(10), test1(5);
test1 = test + 10;	//正常执行
test1 = 10 + test;	//编译错误

所以使用友元函数可以解决此问题

// Test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <algorithm>

using namespace std;

class Test
{
public:
	Test();
	Test(int value) :m_value(value) {}
	~Test();

	//重载 + 运算符  - * / %运算符类似
	const Test& operator + (const Test &test) const;
	//重载赋值运算符
	const Test& operator = (const Test &test);

	//二元运算符建议用友元函数的方式重载
	friend Test operator + (int intValue, const Test &test);

	//流运算符一般只能用友元的方式重载
	//今后就可以重载流运算符,以便封装某个对象的打印格式
	friend ostream & operator << (ostream &out,const Test &test);

	//重载输入运算符
	friend istream & operator >> (iostream &cin, Test &test);
	int GetValue() { return m_value; }
private:
	int	m_value;
};

Test::Test():m_value(0)
{
	cout << "调用无参构造函数" << endl;
}

Test::~Test()
{
}
//重载 + 运算符
const Test& Test::operator + (const Test & test) const
{
	Test T(this->m_value + test.m_value);
	return T;
}
const Test& Test::operator = (const Test &test)
{
	if (this == &test) return *this;		//判断是否是给自己赋值
	this->m_value = test.m_value;
	return *this;	//返回当前对象的引用
}
//友元函数不需要域运算符了
Test operator + (int intValue, const Test &test)
{
	return Test(intValue + test.m_value);
}
//流运算符一般只能用友元的方式重载
ostream & operator << (ostream &out, const Test &test)
{
	out << test.m_value;
	return out;
}
istream & operator >> (iostream &cin, Test &test)
{
	cin >> test.m_value;
	return cin;
}
void main()
{
	Test test(10), test1(5);

	Test test2 = 10 + test + 10;
	cout << test2.GetValue() << endl;

	cout << test << endl;

	system("pause");
}

友元函数破坏了类的封装性,一般不建议使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值