c++-友元函数和友元类
程序员文章站
2023-11-09 18:17:22
友元函数 + 友元函数和友元类(破坏类的封装性) + 面向对象编程思想 ......
友元函数
- 友元函数和友元类(破坏类的封装性)
- 面向对象编程思想
#define _crt_secure_no_warnings #include <iostream> #include <cmath> using namespace std; class point; class pointmanager { public: double pointdistance(point &p1, point &p2); }; class point { public: //声明全局函数 pointdistance 是我类point类的一个友元函数。 //friend double pointdistance(point &p1, point &p2); friend double pointmanager::pointdistance(point &p1, point &p2); point(int x, int y) { this->x = x; this->y = y; } int getx() { return this->x; } int gety() { return this->y; } private: int x; int y; }; double pointmanager::pointdistance(point &p1, point &p2) { double dis; int dd_x = p1.x - p2.x; int dd_y = p1.y - p2.y; dis = sqrt(dd_x*dd_x + dd_y *dd_y); return dis; } # if 0 double pointdistance(point &p1, point &p2) { double dis; int dd_x = p1.x - p2.x; int dd_y = p1.y - p2.y; dis = sqrt(dd_x*dd_x + dd_y *dd_y); return dis; } #endif int main(void) { point p1(1, 2); point p2(2, 2); //cout << pointdistance(p1, p2) << endl; pointmanager pm; cout << pm.pointdistance(p1, p2) << endl; return 0; }
友元类
#define _crt_secure_no_warnings #include <iostream> using namespace std; class a { public: a(int a) { this->a = a; } void printa() { cout << "a = " << this->a << endl; // b objb(3000); // cout << objb.b << endl; } //声明一个友元类b friend class b; private: int a; }; class b { public: b(int b) { this->b = b; } void printb() { a obja(100); cout << obja.a << endl; cout << "b = " << this->b << endl; } friend class a; private: int b; }; int main(void) { b bobj(200); bobj.printb(); return 0; }
上一篇: hive工作记录-20180513
下一篇: Swoole协程与传统fpm同步模式比较