分别说明了类Pixel的两个友元函数:一个全局函数getDist()Pixel,pixel;另一个类Test的成员函数printX(Pixel p);
要说明printX(Pixel p)是友元函数,必须要现有类Test的全部定义。而类Test又用到了Pixel所以需要将Pixel在类Test进行声明。
在主函数中调用全局友元函数时直接写函数名就可以。
调用类内部的成员函数时,必须通过类的对象才可以实现。
因为两个都是类Pixel的友元,所以在函数内部均可直接访问Pixel的私有成员变量x和y。
#include <iostream> #include <cmath> using namespace std; class Pixel; //向前引用声明 class Test { public: void printX(Pixel p); //用到了类Pixel }; class Pixel { private: int x, y; public: Pixel(int x0, int y0) { x = x0; y = y0; } void printxy() { cout << "(pixel:(" << x << "," << y << ")" << endl; } friend double getDist(Pixel p1, Pixel p2); //友元函数(原型) 全局函数 friend void Test::printX(Pixel p); //类Test的成员函数为本类的友元函数 }; void Test::printX(Pixel p) { cout << "x=" << p.x << "\ty=" << p.y << endl; //访问类Pixel的私有成员 return; } double getDist(Pixel p1, Pixel p2) //友元函数在类体外定义 { double xd = double(p1.x - p2.x);//使用类Pixel的私有成员x double yd = double(p1.y - p2.y);//使用类Pixel的私有成员y return sqrt(xd * xd + yd * yd);//两点间距离 } int main() { Pixel p1(0, 0), p2(10, 10); p1.printxy(); p2.printxy(); cout << "(p1,p2)间距离=" << getDist(p1, p2) << endl;//直接调用全局函数 Test t; cout << "从友元函数中输出" << endl; t.printX(p1);//通过对象调用类的成员函数 t.printX(p2);//通过对象调用类的成员函数 return 0; }
运行结果