C ++构造函数定义在以下代码中的区别 [英] C++ constructor definition differences in the code given below
本文介绍了C ++构造函数定义在以下代码中的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C ++的新手.学习构造函数.请参考下面提到的两个代码,并提供原因,为什么代码2不起作用.谢谢.
I am newbie to C++. Learning constructors. Please refer to two codes mentioned below, and provide reason, why Code 2 is not working. Thanks.
代码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却不能正常工作?
Why the code 1 is working but Code 2 is NOT working?
推荐答案
出于某些奇怪的原因,不允许您重复参数的默认值:
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;
}
这篇关于C ++构造函数定义在以下代码中的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文