c++ - const 对象未初始化的编译器投诉

标签 c++ constructor constants default-constructor

<分区>

Possible Duplicate:
uninitialized const

我知道需要初始化一个 const 对象。

所以对于下面的代码,

class sample
{};

int main()
{
   const sample obj;
   return 0;
}

编译器会报错,因为 const 对象 obj 没有初始化。

但是当我使用默认构造函数修改代码(如下所示)时,编译器不会抛出任何错误。

class sample
{
    public:
       sample() { }
};

int main()
{
    const sample obj;
    return 0;
}

新添加的默认ctor做了什么让编译器满意的事情?

最佳答案

新添加的默认ctor做了什么让编译器满意的事情?

因为这是 C++ 标准在使用 const 限定符声明对象时强加的要求。

引用:

C++03 8.5 初始化器 8 声明器
§9:

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value90); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

关于c++ - const 对象未初始化的编译器投诉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8952284/

相关文章:

c++ - 为什么对堆栈中的内存使用自定义动态内存分配?

python - OpenCV-contrib/Python/Windows:Tracker.write()在matrix_wrap.cpp中引发错误,Tracker.read()使Python崩溃

c++ - C2259 : 'ID3D11ShaderResourceView' Cannot instantiate abstract class - DX11

c# - 使用隐式/显式转换而不是构造函数的原因是什么?

c# - 为什么构造函数不接受可访问性较低的类的参数?

c++ - 删除指向 const (T const*) 的指针

c++ - 参数包的模板推导和显式提供的类型

java - 类设计 - 从字符串数据创建对象?

c++ - const 成员函数中的成员变量类型

c++ - 为什么第一个程序不起作用但第二个程序有效?第二,为什么输出是它给出的?