简体   繁体   English

为什么我们不能在 C++ 中初始化类的成员变量

[英]Why we cannot initialize the member variable of a class in C++

It's giving error:它给出了错误:

#include <iostream>
using std::cout;

class stud
{
    int a = 0; // error??

public:
    void display();
};

int main()
{
    // ...
}

(The cause) (原因)

Non-static data member with a default member initializer is supported since C++11. 从C ++ 11开始,支持带有默认成员初始化程序的非静态数据成员。

-- -

(The fix) (修复)

These days, many compilers support C++11. 如今,许多编译器都支持C ++ 11。

For Visual Studio IDE users (like myself): On project properties: C/C++ > Language > C++ Language Standard: Set to C++11 or above. 对于Visual Studio IDE用户(例如我自己):在项目属性上:C / C ++>语言> C ++语言标准:设置为C ++ 11或更高版本。 In Visual Studio 2017 C++11 is supported at baseline. 在Visual Studio 2017中,基线支持C ++ 11。

For other than Visual Studio IDE users, search the topic: "How to enable C++11" for your compiler. 对于非Visual Studio IDE用户,请搜索主题:“如何启用C ++ 11”以供您的编译器使用。

It is possible to do this from C++11 onwards . 从C ++ 11 开始可以执行此操作。

Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list. 通过默认成员初始化程序,该成员初始化程序只是成员声明中包含的花括号或等于初始值设定项,如果在成员初始化程序列表中省略了该成员,则使用该默认值。

class S
{
    int n = 7;
    std::string s{'a', 'b', 'c'};
    S() // copy-initializes n, list-initializes s
    { }
};

In the class, we usually declare all the variables in private section. 在类中,我们通常在私有部分声明所有变量。 And we do not initialize them in the class. 而且我们不在类中初始化它们。 You can use the constructor in order to initialize them. 您可以使用构造函数来对其进行初始化。

class stud {

private:

    int a;

public:

    stud();
};

stud::stud() 
{

int a = 5; // initialize here..

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM