代码如下:#include <iostream> using namespace std; class Teacher { public: Teacher(char *temp) { director = new char[10]; strcpy(director,temp); } ~Teacher() { cout<<"释放堆区director内存空间1次"; delete[] director; cin.get(); } char *show(); protected: char *director; }; char *Teacher::show() { return director; } class Student { public: Student(char *temp):teacher(temp) { number = 1; score = 100; } void show(); protected: int number; int score; Teacher teacher; }; void Student::show() { cout<<teacher.show()<<endl<<number<<endl<<score<<endl; } void main() { Student a("王大力"); a.show(); //Student b[5]("王大力"); //这里这么用是不对的,数组不能够使用带参数的构造函数,以后我们将详细介绍vector类型 // for(int i=0; i<sizeof(b)/sizeof(Student); i++) //{ // b[i].show(); //} cin.get(); } 大家可以发现最明显的改变在这里
Student(char *temp):teacher(temp)
冒号后的teacher就是告诉调用Student类的构造函数的时候把参数传递给成员teacher的Teacher类的构造函数,这样一来我们就成功的在类体外对teacher成员进行了初始化,既方便也高效,这种冒号后指定调用某成员构造函数的方式,可以同时制定多个成员,这一特性使用逗号方式,例如:
Student(char *temp):teacher(temp),abc(temp),def(temp)
由冒号后可指定调用哪那个类成员的构造函数的特性,使得我们可以给类的常量和引用成员进行初始化成为可能。
我们修改上面的程序,得到如下代码: #include <iostream> #include <string> using namespace std; class Teacher { public: Teacher(char *temp) { director = new char[10]; strcpy(director,temp); } ~Teacher() { cout<<"释放堆区director内存空间1次"; delete[] director; cin.get(); } char *show(); protected: char *director; }; char *Teacher::show() { return director; } class Student { public: Student(char *temp,int &pk):teacher(temp),pk(pk),ps(10) { number = 1; score = 100; } void show(); protected: int number; int score; Teacher teacher; int &pk; const int ps; }; void Student::show() { cout<<teacher.show()<<endl<<number<<endl<<score<<endl<<pk<<endl<<ps<<endl; } void main() { char *t_name="王大力"; int b=99; Student a(t_name,b); a.show(); cin.get(); } 改变之处最重要的在这里Student(char *temp,int &pk):teacher(temp),pk(pk),ps(10)
调用的时候我们使用
Student a(t_name,b);
我们将b的地址传递给了int &pk这个引用,使得Student类的引用成员pk和常量成员ps进行了成功的初始化。
|