为什么不能在c++中初始化类中的变量

why you can not initialize the variable inside the class in c++

本文关键字:变量 初始化 为什么 c++ 不能      更新时间:2023-10-16

我知道不使用构造函数就不能在类内部直接初始化成员变量(除了静态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支持这个