使用友元函数和运算符重载
友元函数
类的友元函数可以访问其任何成员。也就是说,尽管Peek()
函数不是Critter
类的成员函
数,但它还是可以访问Critter
的任意成员——Peek()
利用这种关系访问私有数据成员
m_Name
。
friend void Peek(const Critter& aCritter);
...
void Peek(const Critter& aCritter)
{
cout << aCritter.m_Name << endl;
}
当 main
函数调用 Peek()
时,crit
的私有数据成员 m_Name
被显示出来。
Peek(crit)
运算符重载
重载运算符的方法:定义一个名为 operatorX
的函数,其中 X
是需要重载的运算符。
ostream& operator<<(ostream& os, const Critter& aCritter)
{
os << "Critter Object - ";
os << "m_Name: " << aCritter.m_Name;
return os;
}
该函数之所以能访问 Critter
对象的私有数据成员 m_Name
,是因为下面这行代码
使得该函数成为 Critter
类的友元:
friend ostream& operator<<(ostream& os, const Critter& aCritter);
源码
#include <iostream>
#include <string>
using namespace std;
class Critter
{
friend void Peek(const Critter& aCritter);
friend ostream& operator<<(ostream& os, const Critter& aCritter);
public:
Critter(const string& name = "");
private:
string m_Name;
};
Critter::Critter(const string& name) :
m_Name(name)
{}
void Peek(const Critter& aCritter);
ostream& operator<<(ostream& os, const Critter& aCritter);
int main()
{
Critter crit("Poochie");
cout << "Calling Peek() to access crit's private data member, m_Name: \n";
Peek(crit);
cout << "\nSending crit object to cout with the << operator:\n";
cout << crit;
return 0;
}
// global friend function that can access all of a Critter object's members
void Peek(const Critter& aCritter)
{
cout << aCritter.m_Name << endl;
}
// global friend function that can access all of a Critter object's members
ostream& operator<<(ostream& os, const Critter& aCritter)
{
os << "Critter Object - ";
os << "m_Name: " << aCritter.m_Name;
return os;
}