// 内部类.cpp : 定义控制台应用程序的入口点。 //内部类,如果一个类定义在另一个类的内部,这个内部类就叫做内部类。注意此时这个内部类是一个独立的类,它不属于外部类,更不能通过外部类的对象去调用内部类。外部类对内部类没有任何优越的访问权限。 //即说:内部类就是外部类的友元类。注意友元类的定义,内部类可以通过外部类的对象参数来访问外部类中的所有成员。但是外部类不是内部类的友元。 //2. 内部类可以定义在外部类的public、protected、private都是可以的。 //1)如果内部类定义在public,则可通过 外部类名::内部类名 来定义内部类的对象。 //2)如果定义在private,则外部不可定义内部类的对象,这可实现“实现一个不能被继承的类”问题。 //3. 注意内部类可以直接访问外部类中的static、枚举成员,不需要外部类的对象/类名。 /* 4. 在堆中创建内部类对象: class A { public: class B{}; }; int _tmain(int argc, _TCHAR* argv[]) { A::B*b=new A::B(); return 0; } 5.内部类可以现在外部类中声明,然后在外部类外定义: class A { private: static int i; public: class B; }; class A::B{ public:void foo(){cout<<i<<endl;}//!!!这里也不需要加A::i. }; int A::i=3; 6. sizeof(外部类)=外部类,和内部类没有任何关系。 class A { public: class B{int o;}; }; int _tmain(int argc, _TCHAR* argv[]) { cout<<sizeof(A)<<endl;//1 return 0; } 总结一下:其实内部类和友元类很像很像。只是内部类比友元类多了一点权限:可以不加类名的访问外部类中的static、枚举成员。其他的都和友元类一样。 */ //----------------------------------------------------------------------接下来是主程序,上面是讲解的博客。 #include "stdafx.h" using namespace std; class Student{ // static int num; int num; string name; public: Student(){} Student(int a,string b):num(a),name(b){} struct Son{ char sex; double sum; Son(){} Son(char c,double d):sex(c),sum(d){} void show(Student student1){ cout << "sex = " << sex << endl; cout << "sum = " << sum << endl; cout << "student1.num = " << student1.num <<endl; //1)当外部类的成员为静态可以直接访问;2)当外部类的成员对象不存在的时侯,内部类是不能访问外部类的,而静态变量是已经存在的,是没有问题的。这和友元类的使用也是同样的道理。“想要使用另一个类的成员,必须要存在这个类的对象”。 cout << "student1.name = " << student1.name << endl; //当外部类不是静态成员的时候,可以在内部类的函数中传参,从而通过外部类的传参对象来访问外部类的成员变量。就像函数的传参一样。 } ~Son(){} }; void show(){ cout << "num = " << num << endl; cout << "name = " << name << endl; } ~Student(){} }; //int Student::num = 1000; int _tmain(int argc, _TCHAR* argv[]) { Student student1(1001,"Mary"); //student1.show(); Student::Son son1('M',3.14); //内部类的初始化,要外部类的域名; son1.show(student1); system("pause"); return 0; }
转载于:https://my.oschina.net/u/3845807/blog/3000556