1、运算符声明成类成员还是声明独立友元函数建议准则:
- C++规定,赋值运算符=、数组下标运算符[]、函数调用运算符、成员访问运算符->在重载时必须声明为类的成员函数
- 流运算符<<、>>、类型转换运算符不能定义类的成员函数,只能是友元函数
- 一元运算符和和赋值运算符重载时,一般声明类的成员函数
- 二元运算符在运算符重载时,一般声明为友元函数
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");
}
友元函数破坏了类的封装性,一般不建议使用