C++ 友元类

it2025-05-05  7

友元 (1)是C++提供的一种破坏数据封装和数据隐藏的机制 (2)通过将一个模块声明为另一个模块的友元,一个模块能引用到另一个模块中本是被隐藏的信息 (3)可以使用友元函数和友元类 (4)为了确保数据的完整性,及数据封装与隐藏的原则,建议尽量不使用或少使用友元

最近使用友元类的一个方向就是做UT/IT(单元测试,集成测试),因为需要自己设定一些数据的值,可能被测目标函数会用到一些私有或全局变量,如果需要对这些数据的值进行改变,要么就是将私有程序类型改为共有类型,这样就好修改被测目标文件,此时,更好的方式就是使用友元类,下面是一个使用的简单的例子。

getVolume.cpp是我们需要测试的源文件,主要对getVolume()、getArea()这两个函数进行测试,由于被测源文件成员函数及成员变量全部为私有类型,从外部无法调用,此时就需要使用友元类来创造数据和测试函数。

getVolume.h

#include <iostream> using namespace std; class Box { public: friend class BoxCaller; private: double getVolume(void); double getArea(void); double length; // 长度 double breadth; // 宽度 double height; // 高度 };

getVolume.cpp

#include <iostream> #include "getVolume.h" using namespace std; double Box::getVolume(void) { return length * breadth * height; } double Box::getArea(void) { return length * breadth; }

测试文件test.cpp

#include <iostream> #include "getVolume.h" using namespace std; class BoxCaller { public: //设置长宽高 void setLength( double len ){ box.length = len; } void setBreadth( double bre ){ box.breadth = bre; } void setHeight( double hei ){ box.height = hei; } //获取长宽高 double getLength(){ return box.length; } double getBreadth(){ return box.breadth; } double getHeight(){ return box.height; } //获取体积 double getVolume(){ return box.getVolume(); } //获取面积 double getArea(){ return box.getArea(); } private: Box box; }; int main() { BoxCaller caller; caller.setLength(5); cout << "length : " << caller.getLength() << endl; caller.setBreadth(6); cout << "breadth : " << caller.getBreadth() << endl; caller.setHeight(7); cout << "height : " << caller.getHeight() << endl; double volume = caller.getVolume(); cout << "volume : " << volume << endl; double area = caller.getArea(); cout << "area : " << area << endl; return 0; }

 

最新回复(0)