内部内:
#include <iostream> using namespace std; class CPeople { public: int a; CPeople( int a ) { this->a = a; } private: class Kayer { public: int a; CPeople* cp; Kayer(CPeople* p) : cp(p) { a = 12; } void fun() { cout << cp->a << endl; } }; public: Kayer* kayer = new Kayer(this); }; int main() { CPeople c( 13 ); cout << "CPeople a : " << c.a << endl; c.kayer->fun(); cout << "=======================================" << endl; c.a = 17; cout << "CPeople a : " << c.a << endl; c.kayer->fun(); return 0; }
结果:
解析 :
① 内部类也属于嵌套类。例如 :Kayer就是CPeople的内部类
② 内部类(Kayer)访问外部类(CPeople)需要使用引用/指针。本篇使用指针 Kayer* kayer = new Kayer(this); 这样可以保证数据的同步。
时间: 2024-10-12 20:15:35