C++ constructor definition differences in the code given below [closed]

不想你离开。 提交于 2019-12-03 00:11:05

问题


I am newbie to C++. Learning constructors. Please refer to two codes mentioned below, and provide reason, why Code 2 is not working. Thanks.

Code 1:

#include <iostream>
using namespace std;

class Box
{
    int x;
public:
    Box::Box(int a=0)
    {
        x = a;
    }
    void print();
};

void Box::print()
{
    cout << "x=" << x << endl;
}

int main()
{
    Box x(100);
    x.print();
}

Code 2:

#include <iostream>
using namespace std;

class Box
{
    int x;
public:
    Box(int a=0);
    void print();
};

Box::Box(int a=0)
{
    x = a;
}

void Box::print()
{
    cout << "x=" << x << endl;
}

int main()
{
    Box x(100);
    x.print();
}

Why the code 1 is working but Code 2 is NOT working?


回答1:


For some odd reasons you are not allowed to repeat the default value for a parameter:

class Box
{
    int x;
public:
    Box(int a=0);
//------------^  given here
    void print();
};

Box::Box(int a=0)
//------------^^  must not be repeated (even if same value)
{
    x = a;
}


来源:https://stackoverflow.com/questions/41509402/c-constructor-definition-differences-in-the-code-given-below

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!