#include <iostream>
using namespace std;
class Part //部件类
{
public:
Part();
Part(int i);
~Part();
private:
int val;
};
class Whole: public Part
{
public:
Whole();
Whole(int,int,int,int);
~Whole();
private:
Part one;
Part two;
int data;
};
Part::Part()
{
val=0;
cout<<"The default constructor of part was called "<<val<<endl;
}
Part::Part(int i)
{
val=i;
cout<<"The constructor of part was called "<<val<<endl;
}
Part::~Part()
{
cout<<"The destructor 33 of part was called "<<val<<endl;
}
Whole::Whole()
{
data=0;
cout<<"The default constructor of whole was called "<<data<<endl;
}
Whole::Whole(int p, int i,int j,int k):Part(p), two(i),one(j),data(k)
{
cout<<"The constructor of whole was called "<<data<<endl;
}
Whole::~Whole()
{
cout<<"The destructor 33 of whole was called "<<data<<endl;
}
int main()
{
Whole w1;
Whole w2(1,2,3,4);
return 0;
}
运行结果:
本文通过一个C++示例程序深入探讨了构造函数与析构函数的工作原理。包括默认构造函数、带参数构造函数及析构函数的调用时机,展示了如何初始化类成员变量并释放资源。
934

被折叠的 条评论
为什么被折叠?



