C++ 如何在类中初始化const成员变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14495536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:22:58  来源:igfitidea点击:

How to initialize const member variable in a class?

c++const

提问by Chaitanya

#include <iostream>

using namespace std;
class T1
{
  const int t = 100;
  public:

  T1()
  {

    cout << "T1 constructor: " << t << endl;
  }
};

When I am trying to initialize the const member variable twith 100. But it's giving me the following error:

当我尝试t用 100初始化 const 成员变量时。但它给了我以下错误:

test.cpp:21: error: ISO C++ forbids initialization of member ‘t'
test.cpp:21: error: making ‘t' static

How can I initialize a constvalue?

如何初始化一个const值?

回答by Dinkar Thakur

The constvariable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution.

const变量指定是否变量是可修改的或没有。每次引用变量时都会使用分配的常量值。在程序执行期间不能修改分配的值。

Bjarne Stroustrup's explanationsums it up briefly:

Bjarne Stroustrup 的解释对其进行了简要总结:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

类通常在头文件中声明,而头文件通常包含在许多翻译单元中。但是,为了避免复杂的链接器规则,C++ 要求每个对象都有唯一的定义。如果 C++ 允许需要作为对象存储在内存中的实体的类内定义,那么这条规则就会被打破。

A constvariable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.

一个const变量要在类中声明,但它不能在它被定义。我们需要在类之外定义 const 变量。

T1() : t( 100 ){}

Here the assignment t = 100happens in initializer list, much before the class initilization occurs.

这里的赋值t = 100发生在初始化列表中,远在类初始化发生之前。

回答by Fred Larson

Well, you could make it static:

好吧,你可以做到static

static const int t = 100;

or you could use a member initializer:

或者您可以使用成员初始值设定项:

T1() : t(100)
{
    // Other constructor stuff here
}

回答by ravs2627

There are couple of ways to initialize the const members inside the class..

有几种方法可以初始化类中的 const 成员。

Definition of const member in general, needs initialization of the variable too..

const 成员的一般定义,也需要变量的初始化..

1) Inside the class , if you want to initialize the const the syntax is like this

1)在类内部,如果要初始化const语法是这样的

static const int a = 10; //at declaration

2) Second way can be

2)第二种方式可以

class A
{
  static const int a; //declaration
};

const int A::a = 10; //defining the static member outside the class

3) Well if you don't want to initialize at declaration, then the other way is to through constructor, the variable needs to be initialized in the initialization list(not in the body of the constructor). It has to be like this

3)好吧,如果你不想在声明时初始化,那么另一种方法是通过构造函数,变量需要在初始化列表中(而不是在构造函数体中)进行初始化。它必须是这样的

class A
{
  const int b;
  A(int c) : b(c) {} //const member initialized in initialization list
};

回答by borisbn

  1. You can upgrade your compiler to support C++11 and your code would work perfectly.

  2. Use initialization list in constructor.

    T1() : t( 100 )
    {
    }
    
  1. 您可以升级编译器以支持 C++11,您的代码将完美运行。

  2. 在构造函数中使用初始化列表。

    T1() : t( 100 )
    {
    }
    

回答by GANESH B K

If you don't want to make the constdata member in class static, You can initialize the constdata member using the constructor of the class. For example:

如果不想使const类中的数据成员成为静态,则可以const使用类的构造函数初始化数据成员。例如:

class Example{
      const int x;
    public:
      Example(int n);
};

Example::Example(int n):x(n){
}

if there are multiple constdata members in class you can use the following syntax to initialize the members:

如果类中有多个const数据成员,您可以使用以下语法来初始化成员:

Example::Example(int n, int z):x(n),someOtherConstVariable(z){}

回答by Musky

Another solution is

另一个解决方案是

class T1
{
    enum
    {
        t = 100
    };

    public:
    T1();
};

So t is initialised to 100 and it cannot be changed and it is private.

所以 t 被初始化为 100 并且它不能被改变并且它是私有的。

回答by Viet Anh Do

If a member is a Array it will be a little bit complex than the normal is:

如果一个成员是一个数组,它会比正常情况稍微复杂一点:

class C
{
    static const int ARRAY[10];
 public:
    C() {}
};
const unsigned int C::ARRAY[10] = {0,1,2,3,4,5,6,7,8,9};

or

或者

int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
public:
  C():v(a, a+N) {}
};

回答by Baran

Another possible way are namespaces:

另一种可能的方式是命名空间:

#include <iostream>

namespace mySpace {
   static const int T = 100; 
}

using namespace std;

class T1
{
   public:
   T1()
   {
       cout << "T1 constructor: " << mySpace::T << endl;
   }
};

The disadvantage is that other classes can also use the constants if they include the header file.

缺点是其他类如果包含头文件,也可以使用这些常量。

回答by Gambler Aziz

This is the right way to do. You can try this code.

这是正确的做法。你可以试试这个代码。

#include <iostream>

using namespace std;

class T1 {
    const int t;

    public:
        T1():t(100) {
            cout << "T1 constructor: " << t << endl;
        }
};

int main() {
    T1 obj;
    return 0;
}

if you are using C++10 Compiler or belowthen you can not initialize the cons member at the time of declaration. So here it is must to make constructor to initialise the const data member. It is also must to use initialiser list T1():t(100)to get memory at instant.

如果您正在使用,C++10 Compiler or below则不能在声明时初始化 cons 成员。所以这里必须让构造函数初始化const数据成员。还必须使用初始化列表T1():t(100)来立即获取内存。

回答by dhokar.w

you can add staticto make possible the initialization of this class member variable.

您可以添加static以使此类成员变量的初始化成为可能。

static const int i = 100;

However, this is not always a good practice to use inside class declaration, because all objects instacied from that class will shares the same static variable which is stored in internal memory outside of the scope memory of instantiated objects.

然而,这并不总是使用类内部声明的好习惯,因为从该类实例化的所有对象将共享相同的静态变量,该变量存储在实例化对象的作用域内存之外的内部内存中。