题目描述
xiaoping刚接触类的构造和析构函数,对于构造函数的编写比较困惑。zhuangzhuang给小平布置了一道题目,xiaoping苦思两天也无法解答,请你帮帮xiaoping吧。
#include <iostream>
using namespace std;
class XiaoPing
{
private:
int state; //用来记录是否有参数
int data;
public:
XiaoPing();
XiaoPing(int data);
~XiaoPing();
};
//////////////////////////////////////////////
只需完成并提交该部分代码
///////////////////////////////////////////////
XiaoPing::~XiaoPing()
{
if(state)
cout<<"destroy an object with a parameter:"<<data<<endl;
else
cout<<"destroy an object with no parameter"<<endl;
}
int main()
{
int data;
XiaoPing zeropara1;
cin>>data;
XiaoPing onepara1(data);
XiaoPing zeropara2;
cin>>data;
XiaoPing onepara2(data);
return 0;
}
输入
输入两行。每行一个整数,表示构造函数的参数值。
输出
按照题意输出构造函数和析构函数的调用顺序和信息。
样例输入
1
2
样例输出
create an object with no parameter create an object with a parameter:1 create an object with no parameter create an object with a parameter:2 destory an object with a parameter:2 destory an object with no parameter destory an object with a parameter:1 destory an object with no parameter
#include <iostream> using namespace std; class XiaoPing { private: int state; //用来记录是否有参数 int data; public: XiaoPing(); XiaoPing(int data); ~XiaoPing(); }; XiaoPing::XiaoPing() { state = 0; cout << "create an object with no parameter" << endl; } XiaoPing::XiaoPing(int n) { data = n; state = 1; cout << "create an object with a parameter:" << data << endl; } XiaoPing::~XiaoPing() { if(state) cout<<"destroy an object with a parameter:"<<data<<endl; else cout<<"destroy an object with no parameter"<<endl; } int main() { int data; XiaoPing zeropara1; cin>>data; XiaoPing onepara1(data); XiaoPing zeropara2; cin>>data; XiaoPing onepara2(data); return 0; }