简体   繁体   English

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

[英]How to initialize const member variable in a class?

#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 t with 100. But it's giving me the following error:当我尝试用 100 初始化 const 成员变量t时。但它给了我以下错误:

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

How can I initialize a const value?如何初始化const值?

The const variable specifies whether a variable is modifiable or not. const变量指定变量是否可修改。 The constant value assigned will be used each time the variable is referenced.每次引用变量时都会使用分配的常量值。 The value assigned cannot be modified during program execution.在程序执行期间不能修改分配的值。

Bjarne Stroustrup's explanation sums 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.但是,为了避免复杂的链接器规则,C++ 要求每个对象都有唯一的定义。 That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.如果 C++ 允许需要作为对象存储在内存中的实体的类内定义,那么这条规则就会被打破。

A const variable has to be declared within the class, but it cannot be defined in it. const变量必须在类中声明,但不能在类中定义。 We need to define the const variable outside the class.我们需要在类之外定义 const 变量。

T1() : t( 100 ){}

Here the assignment t = 100 happens in initializer list, much before the class initilization occurs.这里赋值t = 100发生在初始化列表中,远在类初始化发生之前。

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
}

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). 3)好吧,如果你不想在声明时初始化,那么另一种方法是通过构造函数,变量需要在初始化列表中(而不是在构造函数体中)进行初始化。 It has to be like this它必须是这样的

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

If you don't want to make the const data member in class static, You can initialize the const data member using the constructor of the class.如果不想使类中的const数据成员成为静态,则可以使用类的构造const初始化const数据成员。 For example:例如:

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

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

if there are multiple const data members in class you can use the following syntax to initialize the members:如果类中有多个const数据成员,您可以使用以下语法来初始化成员:

Example::Example(int n, int z):x(n),someOtherConstVariable(z){}
  1. You can upgrade your compiler to support C++11 and your code would work perfectly.您可以升级编译器以支持 C++11,您的代码将完美运行。

  2. Use initialization list in constructor.在构造函数中使用初始化列表。

     T1() : t( 100 ) { }

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 并且它不能被改变并且它是私有的。

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) {}
};

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.缺点是其他类如果包含头文件,也可以使用这些常量。

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 below then you can not initialize the cons member at the time of declaration.如果您使用的是C++10 Compiler or below则无法在声明时初始化 cons 成员。 So here it is must to make constructor to initialise the const data member.所以这里必须让构造函数初始化const数据成员。 It is also must to use initialiser list T1():t(100) to get memory at instant.还必须使用初始化列表T1():t(100)来立即获取内存。

you can add static to 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.然而,这并不总是使用类内部声明的好习惯,因为从该类实例化的所有对象将共享相同的静态变量,该变量存储在实例化对象的作用域内存之外的内部内存中。

In C++ you cannot initialize any variables directly while the declaration.在 C++ 中,您不能在声明时直接初始化任何变量。 For this we've to use the concept of constructors.为此,我们必须使用构造函数的概念。
See this example:-请参阅此示例:-

#include <iostream>

using namespace std;

class A
{
    public:
  const int x;  
  
  A():x(0) //initializing the value of x to 0
  {
      //constructor
  }
};

int main()
{
    A a; //creating object
   cout << "Value of x:- " <<a.x<<endl; 
   
   return 0;
}

Hope it would help you!希望能帮到你!

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

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