c++的友元类、方法及其益处
在java中,我们知道除了public和private,protected外,还有默认的包可见性访问级别,虽然如此,很多时候出于早期设计缺陷的原因,我们需要访问一些包或者protected可见性级别的方法,这个时候就比较麻烦了,要是选择和目标服务在相同包中,总看起来很奇怪,如果作为子类继承,则更加奇怪。但是我们又不想把该接口服务的可见性声明为public。
c++中,这一点做的就比较好,我们知道在c++中,有友元类、方法的特性,该特性相当于白名单的作用,当一个类或者成员函数、非OO函数被声明为目标类的友元时,它可以访问任何包括private的成员熟悉、函数。如下所示:
#pragma once class Base { int j; public: int i; //仅为了测试方便 Base(void); ~Base(void); virtual void testDynCast(); friend void globalFriend(); //友元函数 friend class FirstCPPCls; //友元类 };
#include "stdafx.h" #include "FirstCPPCls.h" #include "Base.h" FirstCPPCls::FirstCPPCls(void) { Base b; b.j = 1; }
这样,就可以精确的按照需要控制可见范围。
另外一个典型的场景式用于重载<<操作符输出对象。如下;
class Goods { public: string name; double _price; double amount; public: friend ostream &operator<<(ostream &os, const Goods &g); Goods(string name, double _price, double amount) { this->name = name; this->amount = amount; this->_price = _price; } }; // 那其实跟写个printf成员函数也没区别,而且内聚性更强,多个同名类也不会冲突 ostream &operator<<(ostream &os, const Goods &g) { cout << g.name << "," << g._price << "," << g.amount << endl; return os; }
其他可以参考下http://blog.chinaunix.net/uid-790245-id-2037327.html