xiaoping学构造函数

xiaoping学构造函数

时间: 1ms        内存:128M

描述:

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

提示:

参考答案(内存最优[1484]):


#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 data)
{
    state = 1;
    this->data = data;
    cout<<"create an object with a parameter:"<<data<<endl;
}
XiaoPing::~XiaoPing()
{
    if(state)
        cout<<"destory an object with a parameter:"<<data<<endl;
    else
        cout<<"destory 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;
}

参考答案(时间最优[0]):


#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 data)
{
    state = 1;
    this->data = data;
    cout<<"create an object with a parameter:"<<data<<endl;
}
XiaoPing::~XiaoPing()
{
    if(state)
        cout<<"destory an object with a parameter:"<<data<<endl;
    else
        cout<<"destory 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;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注