class Tyre { private: int radius; int width; public: Tyre(int r, int w):radius(r), width(w) { } }; class Engine { };
class Car { // 这个类就是所谓的封闭类 //其中包括成员对象Engine和Tyre private: int price; Tyre tyre; Engine engine; public: Car(int p, int tr, int tw); }; Car::Car(int p, int tr, int w):price(p), tyre(tr, w){ }; int main(){ Car car(20000,17,225); return 0; }
class Tyre { public: Tyre() { cout << "Tyre contructor" << endl; } ~Tyre() { cout << "Tyre destructor" << endl; } }; class Engine { public: Engine() { cout << "Engine contructor" << endl; } ~Engine() { cout << "Engine destructor" << endl; } }; 7 class CCar { private: Engine engine; Tyre tyre; public: Car( ) { cout << “Car contructor” << endl; } ~Car() { cout << "Car destructor" << endl; } }; int main(){ Car car; return 0; }
#include<iostream> using namespace std; class Date { public: Date( ){ cout<<"This is Date"<<endl; } //Date的缺省构造函数 Date(int A) { cout<<"The value="<<A<<endl; }; class Time { public: Time( ) {cout<<"This is Time"<<endl; //Time的缺省构造函数 Time(int A):d2( A ) //Time的构造函数。采用成员初始化列表的方式,成员对象d1的形参未初始化 ,将成员对象d2的形参初始化为A { cout<<"Hello!"<<endl; } private: Date d1 , d2; //在Time中声明两个数据成员d1和d2,这两个成员是Date类的两个对象,即d1和d2是成员对象 }; void main( ) { Time t1, t2(6); //注释1 cout<<"The end"<<endl; }
讲讲c++ Session 5:成员对象(Member objects)和封闭类(Enclosing class)
原文地址:http://blog.csdn.net/p641290710/article/details/41256113