主题
友元
成员函数的局限
上一节的 Time 类重载了 operator*,能用 a * 2.0。但 2.0 * a 不行——因为成员函数的左操作数必须是本类对象,而这里左边是 double。类似地,想让 std::cout << a 直接打印对象也不行,因为 << 的左操作数是 std::ostream,不是你的类。
解决这类"左操作数不是本类"的问题,有两种思路:
- 写一个非成员函数,两个操作数都作为参数。
- 但非成员函数访问不了类的
private成员——于是需要友元机制授权它访问。
什么是友元
友元函数不是类的成员,但被类授予了访问其 private 成员的权限。声明方式:在类内写函数原型,前面加 friend 关键字。
cpp
// timev2.h
#ifndef TIMEV2_H_
#define TIMEV2_H_
#include <iostream>
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
Time operator+(const Time& t) const;
Time operator*(double n) const; // 成员版:a * n
// 友元版:n * a,左操作数是 double
friend Time operator*(double n, const Time& t);
// 友元版:cout << a,左操作数是 ostream
friend std::ostream& operator<<(std::ostream& os, const Time& t);
int totalMinutes() const { return hours * 60 + minutes; }
};
#endiffriend 声明写在类内,但函数本身不是成员:它没有 Time:: 限定,也不能用 this。它之所以能访问 t.hours、t.minutes 这些私有成员,全靠 friend 授权。
实现 double 乘 Time
cpp
// timev2.cpp
#include "timev2.h"
Time::Time() : hours(0), minutes(0) {}
Time::Time(int h, int m) : hours(h), minutes(m) {}
Time Time::operator+(const Time& t) const
{
int total = totalMinutes() + t.totalMinutes();
return Time(total / 60, total % 60);
}
Time Time::operator*(double n) const
{
long m = static_cast<long>(totalMinutes() * n);
return Time(m / 60, m % 60);
}
// 友元函数:定义时不写 Time::,也不写 friend
Time operator*(double n, const Time& t)
{
return t * n; // 复用成员版 operator*
}
// 友元函数:直接访问 t.hours、t.minutes
std::ostream& operator<<(std::ostream& os, const Time& t)
{
os << t.hours << " 时 " << t.minutes << " 分";
return os; // 返回流引用,支持链式 <<
}要点:
- 友元函数定义时不写
friend,也不写Time::——它就是个普通函数,只是被授权了。 operator*(double, const Time&)里直接return t * n;,复用成员版的operator*,避免重复逻辑。operator<<返回std::ostream&,是为了能写std::cout << a << b << "\n";——每次<<返回流本身,接着下一个<<继续用。
使用友元
cpp
#include <iostream>
#include "timev2.h"
int main()
{
Time a(2, 30);
Time b(1, 15);
std::cout << "a = " << a << "\n"; // 友元 operator<<
std::cout << "a + b = " << (a + b) << "\n";
std::cout << "a * 2 = " << (a * 2.0) << "\n"; // 成员版
std::cout << "3 * a = " << (3.0 * a) << "\n"; // 友元版
return 0;
}std::cout << a 被解析成 operator<<(std::cout, a),调用友元函数。链式 std::cout << a << "\n" 等价于 (std::cout << a) << "\n":先调一次返回 std::cout,再对它 << "\n"。
常用的友元:输入输出
operator<< 和 operator>> 几乎总是写成友元,因为左操作数是流(std::ostream/std::istream),不是你的类。套路一致:
cpp
class Note
{
std::string text;
int page;
public:
Note(const std::string& t = "", int p = 0) : text(t), page(p) {}
friend std::ostream& operator<<(std::ostream& os, const Note& n);
friend std::istream& operator>>(std::istream& is, Note& n);
};
std::ostream& operator<<(std::ostream& os, const Note& n)
{
os << n.page << ": " << n.text;
return os;
}
std::istream& operator>>(std::istream& is, Note& n)
{
is >> n.page;
std::getline(is >> std::ws, n.text); // 跳过空白后读整行
return is;
}注意输入版本第二个参数是引用(不是 const),因为要往对象里写数据。
友元的取舍
友元不是滥用的工具。它破坏了封装——给了外部函数直通私有成员的特权。能用 public 接口完成的,就别用友元。常见该用友元的场景:
operator<<、operator>>:左操作数是流,必须非成员。- 某运算符的左操作数不是本类(如
double * Time)。 - 两个类需要紧密协作、互相访问对方私有成员。
如果一个友元函数只是想调用类的 public 方法就能完成工作,那它根本不需要是友元——改成普通非成员函数即可。
课后练习
- 双向乘法:给
Duration类(或上一节的Time)补一个友元operator*(double, const Duration&),让2.5 * d和d * 2.5都能用。友元版内部复用成员版。 - 重载输出:给
Lamp类写一个友元operator<<,让std::cout << lamp能直接打印房间名和亮度。测试链式std::cout << l1 << " " << l2 << "\n"。 - 重载输入:给
Lamp写友元operator>>,从std::cin读入房间名和亮度并写入对象。测试读入后立刻用<<打印确认。 - 友元必要性判断:写一个只需要调用
public方法就能完成的外部函数(比如打印某对象并和另一对象比较),把它先写成友元、再改成普通非成员函数,对比哪种更合理,体会"能用 public 接口就别用友元"。