#include<iostream> using namespace std; class Part //部件类 { public: Part(); Part(int i); ~Part(); private: int val; }; Part::Part() { val=0; cout<<"调用Part的默认构造函数:"<<val<<endl; } Part::Part(int i) { val=i; cout<<"调用Part的构造函数: "<<val<<endl; } Part::~Part() { cout<<"调用Part的析构函数: "<<val<<endl; } class Whole: public Part { public: Whole(); Whole(int,int,int,int); ~Whole(); private: Part one; Part two; int data; }; Whole::Whole() { data=0; cout<<"调用whole的默认构造函数: "<<data<<endl; } Whole::Whole(int p, int i,int j,int k):Part(p),one(j),two(i),data(k) //问题2 { cout<<"调用whole的构造函数: "<<data<<endl; } Whole::~Whole() { cout<<"调用whole的析构函数: "<<data<<endl; } void f() { Whole w1; Whole w2(1,2,3,4); } int main() { f(); return 0; }
运行结果:
Whole::Whole(int p, int i,int j,int k): Part(p),two(i),one(j),data(k) //问题2
这大概是说初始化要按照顺序吧。
时间: 2024-10-06 23:01:09