在下面的代码中,我在创建基类时为未初始化的类成员赋值。为什么这不会导致运行时错误?
class Foo {
public:
Foo(std::string) {}
};
class Bar : public Foo {
public:
Bar() : Foo(s = f()) {} // assigning to uninitialized class member
void print() {
std::cout << s << std::endl;
}
std::string f() {
return "Some string";
}
private:
std::string s;
};
int main()
{
Bar b;
b.print();
return 0;
}
但是向类 Bar 添加另一个成员会在创建 Foo 类时产生错误:
Class Bar {
// same as above
private:
std::string s;
int a; // adding another member
};
为什么会发生这种情况?