构造函数不设置成员变量

Gui*_*nal 7 c++ constructor class

我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Foo() called
Foo(int) called
foo.bar is 5
Run Code Online (Sandbox Code Playgroud)

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

nos*_*sid 12

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

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

构造函数委派的工作方式如下:

Foo(int b)
    : Foo()
{
    bar += b;
    cout << "Foo(int) called" << endl;
}
Run Code Online (Sandbox Code Playgroud)

但是,这只适用于C++ 11.