2012-05-25 69 views
7

我的代码:构造不设置成员变量

#include <iostream> 
using namespace std; 

class Foo 
{ 
public: 
    int bar; 

    Foo() 
    { 
     bar = 1; 
     cout << "Foo() called" << endl; 
    } 

    Foo(int b) 
    { 
     bar = 0; 
     Foo(); 
     bar += b; 
     cout << "Foo(int) called" << endl; 
    } 
}; 

int main() 
{ 
    Foo foo(5); 
    cout << "foo.bar is " << foo.bar << endl; 
} 

输出:

Foo() called 
Foo(int) called 
foo.bar is 5 

为什么不是foo.bar值6? Foo()被调用,但不会将bar设置为1.为什么?

+4

'美孚();'创建未命名的临时对象并立即销毁它。你预期会发生什么? – ildjarn

回答

12

在以下构造函数中,Foo()的行不会委托给以前的构造函数。相反,它会创建一个类型为Foo的新临时对象,与*this无关。

Foo(int b) 
{ 
    bar = 0; 
    Foo(); // NOTE: new temporary instead of delegation 
    bar += b; 
    cout << "Foo(int) called" << endl; 
} 

构造代表团的工作原理如下:

Foo(int b) 
    : Foo() 
{ 
    bar += b; 
    cout << "Foo(int) called" << endl; 
} 

然而,这是唯一可能与C++ 11。

+0

+1注意“只能用C++ 11” - > http://meta.stackexchange.com/q/133642/186397。 – Drise

2

因为你有这条线在构造函数中:

bar = 0; 

您试图调用其它的构造与第二构造Foo()通话,但它只是创建一个临时Foo实例。

3

你不能像普通函数那样使用构造函数。在调用Foo()的代码中,在堆栈中创建一个新对象。

相关问题