您的位置:首页 > 编程语言 > C语言/C++

Problem with ctor in C++

2011-05-22 10:54 288 查看
 

        Sometimes you've got to admit that you're stupid when you did do
something really stupid. I wrote some code that makes myself crashed several
days ago. I mark it down now and tt can be simplified like the following:

 

 

#include <stdio.h>
class A {
public:
A(int x, int y) { a1 = x; a2 = y; a3 = 0; }
A(int z) { A(1, 2); a3 = z; }
public:
int a1;
int a2;
int a3;
};
int main()
{
A a(3);
printf("a1 = %d, a2 = %d, a3 = %d/n", a.a1, a.a2, a.a3);
}


 

 

        Don't ask me why I'm too silly to write one ctor to
initialize three int -_-!!,  this code is just simple enough to illustrate the
problem. It seems fine at the first glance but actually it may ruin your whole
life especially when code go far more complicated in inheritance hierarchy. If
you do not figure it out, let's look at line 5,in fact
A(1, 2); doesn't do anything you expected; Unfortunately it's
not a function call to initialize
the this object instead it calls A::A() to initialize
a temporary, local object (not this), then it
immediately destructs that temporary when control flows over the
;(semicolon), this means you left a1 and a2 uninitialized. In C++ one
constructor cannot call another constructor of the same class,  and one of the
solutions to the problem above can be:

 

 

#include <stdio.h>
class A {
public:
A(int x, int y) { Init(x, y); }
A(int z) { Init(1, 2); a3 = z; }
private:
void Init(int x, int y) { a1 = x; a2 = y; a3 = 0; }
public:
int a1;
int a2;
int a3;
};
int main()
{
A a(3);
printf("a1 = %d, a2 = %d, a3 = %d/n", a.a1, a.a2, a.a3);
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  constructor object c++ class go c