我的代码:构造不设置成员变量
#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.为什么?
'美孚();'创建未命名的临时对象并立即销毁它。你预期会发生什么? – ildjarn