初始化类变量的正确位置? [英] Correct place to initialize class variables?

查看:58
本文介绍了初始化类变量的正确位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化类数据成员的正确位置在哪里?我在这样的头文件中有类声明:

Where is the correct place to initialize a class data member? I have the class declaration in a header file like this:

Foo.h:

class Foo {
private:
    int myInt;
};

然后我尝试在相应的.cpp文件中为myInt设置一个值:

Then I try to set a value to myInt in the corresponding .cpp file:

Foo.cpp:

int Foo::myInt = 1;

我收到重新定义myInt的编译器错误.我在做什么错了??

I get a compiler error for redefining myInt. What am I doing wrong???

推荐答案

您所拥有的是一个实例变量.该类的每个实例都获得自己的myInt副本.初始化它们的地方是在构造函数中:

What you have there is an instance variable. Each instance of the class gets its own copy of myInt. The place to initialize those is in a constructor:

class Foo {
private:
    int myInt;
public:
    Foo() : myInt(1) {}
};

一个类变量是该类的每个实例仅共享一个副本的变量.可以按照您的尝试进行初始化.(有关语法,请参见JaredPar的答案)

A class variable is one where there is only one copy that is shared by every instance of the class. Those can be initialized as you tried. (See JaredPar's answer for the syntax)

对于整数值,还可以选择在类定义中初始化静态const:

For integral values, you also have the option of initializing a static const right in the class definition:

class Foo {
private:
    static const int myInt = 1;
};

这是无法更改的类的所有实例共享的单个值.

This is a single value shared by all instances of the class that cannot be changed.

这篇关于初始化类变量的正确位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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