这些C ++代码之间有什么区别?
我正在尝试使用此构造函数代码,并对其工作方式感到困惑.
I was trying this constructor code and got confused with how it works..
#include<iostream>
using namespace std;
class XYZ{
int a,b;
public:
XYZ(int i, int j):a(i), b(a*j){}
void show(){
cout<<a<<"\t"<<b<<"\n";
}
};
int main(){
XYZ X(2,3);
X.show();
return 0;
}
它给出了预期的结果,但是
it gives the expected results but,
#include<iostream>
using namespace std;
class XYZ{
int b,a;
public:
XYZ(int i, int j):a(i), b(a*j){}
void show(){
cout<<a<<"\t"<<b<<"\n";
}
};
int main(){
XYZ X(2,3);
X.show();
return 0;
}
给出意外的结果.
唯一的区别是 int a,b
和 int b,a
以及 XYZ(int i,int j):a(i),b(a * j){}
的工作原理如何?
嗯,您已经发现了区别.这是非常重要的一个.不管类成员在构造函数的成员初始化器列表中出现的顺序如何,都将按照它们在类定义中出现的顺序对其进行初始化.而且,由于 b
的初始化取决于 a
的值,因此必须首先初始化 a
,这一点很重要.这就是为什么这样的原因:
Well, you already spotted the difference. And it's quite an important one. Members of a class are initialized in the order in which they appear in the class definition, regardless of the order they appear in the constructor's member initializer list. And since the initialization of b
depends on the value of a
, it is important that a
should be initialized first. That's why this works:
int a,b;
但这不是:
int b,a;
如果编写构造函数以使这些依赖项不存在,则更好(更不易出错).这样您就不必担心声明的顺序了.
It would be better though(much less error prone) if you write your constructor such that these dependencies don't exist. Then you don't have to worry about the order of declaration.
XYZ(int i, int j):a(i), b(i*j){}