C++下面给出的代码中的构造函数定义差异

C++ constructor definition differences in the code given below

本文关键字:构造函数 定义 代码 C++      更新时间:2023-10-16

我是C++新手。学习构造函数。请参考下面提到的两个代码,并提供代码 2 不起作用的原因。谢谢。

代码 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();
}

代码 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();
}

为什么代码 1 有效,但代码 2 不起作用?

由于一些奇怪的原因,不允许重复参数的默认值:

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;
}