C++标准(第8.5节)说:
如果程序要求对const限定类型T的对象进行默认初始化,则T应为具有用户提供的默认构造函数的类类型.
为什么?在这种情况下,我无法想到为什么需要用户提供的构造函数.
struct B{
B():x(42){}
int doSomeStuff() const{return x;}
int x;
};
struct A{
A(){}//other than "because the standard says so", why is this line required?
B b;//not required for this example, just to illustrate
//how this situation isn't totally useless
};
int main(){
const A a;
}
Run Code Online (Sandbox Code Playgroud) #include <iostream>
class A {
public:
void foo() const {
std::cout << "const version of foo" << std::endl;
}
void foo() {
std::cout << "none const version of foo" << std::endl;
}
};
int main()
{
A a;
const A ac;
a.foo();
ac.foo();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码无法编译,你能不能告诉我为什么?
可能重复:
未初始化的常量
我知道需要初始化 const 对象。
所以对于下面的代码,
class sample
{};
int main()
{
const sample obj;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器会抱怨,因为 const 对象obj
没有初始化。
但是当我使用默认构造函数修改代码(如下所示)时,编译器不会抛出任何错误。
class sample
{
public:
sample() { }
};
int main()
{
const sample obj;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
新添加的默认ctor做了哪些让编译器满意的事情?
当我尝试使用g ++编译以下内容时:
const int zero;
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个错误uninitialized const 'zero'
.我认为全局变量默认初始化为0 [1]?为什么不是这种情况?
VS编译这个罚款.
[1]例如,请参阅/sf/answers/764910541/