为什么不能在类中定义变量? [英] Why can't I define variables in classes?

查看:181
本文介绍了为什么不能在类中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我定义一个变量,并在类中同时给它一个值,我得到一个错误。这是什么原因?

Whenever I define a variable and give it a value at the same time inside a class, I get an error. What is the reason for this?

如你所见,这不起作用...

As you can see, this doesn't work...

class myClass {
    private:
        int x = 4; // error
};

但是当我保持变量undefined时:

But when I keep the variable undefined it does:

class myClass {
    private:
        int x;
};


推荐答案

由于没有其他人使用成员初始化,将介绍你:

Since no one else is using member initialization, I'll introduce you:

class myClass {
    private:
        int x;
    public:
        myClass() : x (4){}
};

在构造函数的主体中使用它总是更好,开始,所有用户定义的成员将已经被初始化,无论你是否这样说。更好地做一次,实际上初始化非用户定义的成员,并且是唯一适用于非静态 const 成员和引用成员。

It's always better to use this over assigning in the body of the constructor, since by the time the body begins, all user-defined members will have already been initialized whether you said so or not. Better to do it once and actually initialize the non-user-defined members, and it is the only method that works for both non-static const members, and reference members.

例如,以下操作将不起作用,因为 x 正在分配到:

For example, the following will not work because x isn't being initialized in the body, it's being assigned to:

class myClass {
    private:
        const int x;
    public:
        myClass() {x = 4;}
};

但是,使用成员初始值设定程序将会,因为你正在初始化它。 p>

Using a member initializer, however, will, because you're initializing it off the bat:

class myClass {
    private:
        const int x;
    public:
        myClass() : x (4){}
};

请注意,您的 int x = 4; 语法是在C ++ 11中完全有效,其中包含任何需要的初始化,所以如果你开始使用它,你会受益。

Note also that your int x = 4; syntax is perfectly valid in C++11, where it subs in for any needed initialization, so you'll benefit if you start using it.

这篇关于为什么不能在类中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆