为什么不能在c++中初始化类中的变量
why you can not initialize the variable inside the class in c++
我知道不使用构造函数就不能在类内部直接初始化成员变量(除了静态const)。
只是想知道这背后的原因是什么。下面是代码片段
如果有人能帮忙
class a
{
int c=5;
// giving error error C2864: 'a::c' : only static const integral data members can be
// initialized within a class
int b;
public:
a():c(1),b(2){}
void h()
{
printf("%d,%d",c,b);
}
};
int main()
{
a l;
l.h();
getchar();
}
其实你可以。
下面是有效的c++ 11代码:
class A
{
int x = 100; //valid in c++11
};
你的编译器可能不支持这个,但是GCC 4.8.0可以很好地编译它。
希望对你有帮助。
类定义主要是为了告诉其他类你的类将有什么接口,它占用多少内存,以及在编译时已经知道的与类相关的任何值(即常量)。在类定义中没有直接的可执行代码(尽管在类定义中定义的函数中可能有可执行代码)。要执行的代码在函数本身的定义中。
编辑:显然c++ 11支持这个
相关文章:
- 为什么C++有不同的变量初始化方式?
- 静态 constexpr 成员变量初始化
- C++不同的变量初始化
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 是变量初始化失败吗?
- 视觉C++:在 DLL 加载期间,全局变量初始化顺序是否具有确定性?
- 类静态变量初始化顺序
- 使用 constinit 变量初始化 constexpr 变量
- 是否可以在不修改父类的情况下将成员变量初始化推迟到继承的类?
- 使用全局变量初始化不同编译单元中的其他全局变量
- 使用默认构造函数引用成员变量初始化错误
- 宏的 if 语句中的变量初始化
- 不稳定的C :每行适应性变化多变量初始化
- 同一函数中的静态函数变量初始化顺序
- C 语言中的静态变量初始化
- 错误:调用'begin(long double [nPoints])'没有匹配函数;使用硬编码的 int 与整数变量初始化向量
- 类POD成员变量初始化
- 尝试捕获类变量初始化的范围
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- 多变量初始化编译器支持