读书人

种类型的const变量必须要定义构造函数

发布时间: 2013-10-02 13:10:38 作者: rapoo

类类型的const变量必须要定义构造函数吗

#include<iostream>
using namespace std;
class B
{
public:
B()
{
b=2;
}
int b;
};
class A
{
public:
A()
{}
int i;
B a;
};
int main()
{

const A aa;
//using A::B;
cout<<sizeof(A)<<endl;
// B b;
}

如果不定义A()
构造函数不行,这个不是编译器自动定义吗?
[解决办法]
主楼的编译错误是 c++ 标准要求的,by c++11 8.5/6
If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

所以 A 必须提供用户自定义的构造函数,即便该构造函数只具有默认合成的功能。

读书人网 >C++

热点推荐