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.bar6?Foo()被调用但未设置bar为 1。为什么?

4

4 回答 4

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。

于 2012-05-25T20:08:33.603 回答
3

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

于 2012-05-25T20:09:52.540 回答
2

因为您在构造函数中有这一行:

bar = 0;

您试图Foo()在第二个构造函数中调用另一个构造函数,但它只是创建一个临时Foo实例。

于 2012-05-25T20:07:20.857 回答
2

您不应该从另一个构造函数调用构造函数

我可以从 C++ 中的另一个构造函数(做构造函数链接)调用构造函数吗?

除非你正在运行 C++11

于 2012-05-25T20:10:55.390 回答