【发布时间】:2013-05-23 15:52:43
【问题描述】:
我有两个版本的 C++ 代码。一个给出问题,另一个不给出:
/*
* This compiles fine
*/
class base {
private:
const char c;
};
int main() {
base b(); // compiles fine
}
/* * 这会产生编译错误 */
class base {
private:
const char c;
};
int main() {
base b; // error: structure 'b' with uninitialized const members
}
注意区别在于“base b()”和“base b”。 我认为两者都会调用默认构造函数,并且由于该类具有 const 字段,因此程序将无法编译。 请帮忙解释一下。
【问题讨论】:
-
你是 C++“最令人头疼的解析”的另一个受害者(你可以谷歌一下):
base b();不是被编译器解析为变量定义,而是作为函数声明——就像int f();或void g();。 (经验法则:编译器可以解释为函数声明的任何东西,它将。)