C++下面给出的代码中的构造函数定义差异
C++ constructor definition differences in the code given below
我是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;
}
相关文章:
- 具有enable_if外部类原型的模板类构造函数定义
- 构造函数定义中类声明中的模板值
- C++中的继承和构造函数定义
- 如何使用模板化构造函数定义演绎指南?
- 构造函数定义C
- 不正确的成员构造函数定义
- 具有虚拟多重继承的构造函数定义
- C++谷歌测试在哪里放置测试夹具构造函数定义
- 模板类定义中的模板构造函数定义
- C++下面给出的代码中的构造函数定义差异
- 带继承的构造函数定义
- 无法访问构造函数定义之外的变量
- 调用构造函数定义中的函数后收到Segmentation Fault 11错误
- 将具有默认值的构造函数定义为组合对象的私有字段
- 防止重新定义构造函数定义的方法
- 继承构造函数-定义可移植的固定大小类型(C++)
- 在类的私有部分为复制构造函数定义原型如何防止类的复制
- 如何指定继承类的构造函数定义
- 了解默认移动构造函数定义
- 理解构造函数定义块的语法变化