构造函数不设置成员变量

Constructor doesn't set member variable

本文关键字:变量 成员 设置 构造函数      更新时间:2023-10-16

我的代码:

#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。为什么?

在下面的构造函数中,带有 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。

你不能

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

因为构造函数中有以下行:

bar = 0;

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

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

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

除非您正在运行 C++11