问题
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