c**********e 发帖数: 2007 | 1 class X {
public:
X(int aa, int bb, int cc)
{ a=aa; b=bb; c=cc;
}
private:
int c; int b; int a;
};
int main () {
X x(1,2,3);
return 0;
}
In the 2nd example, the constructor is
X(int aa, int bb, int cc): a(aa), b(bb), c(cc) {}
In the 3rd example, the constructor is
X(int a, int b, int c): a(a), b(b), c(c) {}
What is the order of initialization in each example? | a**********s 发帖数: 588 | 2 initialization is always in the order of c, b, a, I think. | c**********e 发帖数: 2007 | 3 It is true for example 2 and 3. It is also true from a textbook.
But for the first example, I put cout statement before a=aa,
before b=bb, before and after c=cc. The order seems opposite.
【在 a**********s 的大作中提到】 : initialization is always in the order of c, b, a, I think.
| p***o 发帖数: 1252 | 4 That's assignment (operator=), not initialization (constructors).
【在 c**********e 的大作中提到】 : It is true for example 2 and 3. It is also true from a textbook. : But for the first example, I put cout statement before a=aa, : before b=bb, before and after c=cc. The order seems opposite.
| c**********e 发帖数: 2007 | 5
It is a user-defined constructor, not operator=. Please see the code
and the result below
【在 p***o 的大作中提到】 : That's assignment (operator=), not initialization (constructors).
| X****r 发帖数: 3557 | 6 As it has been pointed out, in your example none of the data
members a, b, and c are initialized when entering X::X. They
are merely assigned inside X::X.
【在 c**********e 的大作中提到】 : : It is a user-defined constructor, not operator=. Please see the code : and the result below
| h*****0 发帖数: 4889 | 7 显然会顺序执行啊……
【在 c**********e 的大作中提到】 : : It is a user-defined constructor, not operator=. Please see the code : and the result below
| B*******g 发帖数: 1593 | 8 如果你的initialization指的是分配空间的话 三个应该都是c,b,a
你可以print &a,&b,&c (不过我不确定能不能通过看heap地址推出内存分配顺序)
【在 c**********e 的大作中提到】 : : It is a user-defined constructor, not operator=. Please see the code : and the result below
| c**********e 发帖数: 2007 | 9 print &a,&b,&c, we get
ffbff9b8 ffbff9b4 ffbff9b0
You are right, for memory allocation, it is in order c, b, a.
Why not sure. I think it is the two are consistent, right?
【在 B*******g 的大作中提到】 : 如果你的initialization指的是分配空间的话 三个应该都是c,b,a : 你可以print &a,&b,&c (不过我不确定能不能通过看heap地址推出内存分配顺序)
| B*******g 发帖数: 1593 | 10 我的理解是:
int是built-in type..所以作为类的member variable内存分配是连续的,如果你是看非
built-in type变量恐怕就不能通过看地址高低来判断内存分配的先后
【在 c**********e 的大作中提到】 : print &a,&b,&c, we get : ffbff9b8 ffbff9b4 ffbff9b0 : You are right, for memory allocation, it is in order c, b, a. : : Why not sure. I think it is the two are consistent, right?
|
|