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:

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?

373897 次浏览

你可以把它改成 static:

static const int t = 100;

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

T1() : t(100)
{
// Other constructor stuff here
}
  1. 您可以升级您的编译器以支持 C + + 11,您的代码将完美工作。

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

    T1() : t( 100 )
    {
    }
    

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

比雅尼·斯特劳斯特鲁普的 解释简要总结道:

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

const变量必须在类中声明,但不能在类中定义。我们需要在类之外定义 const 变量。

T1() : t( 100 ){}

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

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

常量成员的定义一般来说,也需要变量的初始化。

1)在类中,如果你想初始化 const 语法是这样的

static const int a = 10; //at declaration

2)第二条路可以是

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


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

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

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

另一个解决办法是

class T1
{
enum
{
t = 100
};


public:
T1();
};

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

另一种可能的方法是名称空间:

#include <iostream>


namespace mySpace {
static const int T = 100;
}


using namespace std;


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

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

如果一个成员是 Array,那么它将比普通的 Array 稍微复杂一点:

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

或者

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


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

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

static const int i = 100;

但是,使用类内声明并不总是一个好的做法,因为从该类实例化的所有对象将共享相同的静态变量,该静态变量存储在实例化对象的范围内存之外的内部内存中。

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

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


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

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

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

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

#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;
}

如果您使用的是 C++10 Compiler or below,那么您就不能在声明时初始化 con 成员。因此,这里必须使构造函数初始化 const 数据成员。它还必须使用初始化列表 T1():t(100)来立即获得内存。

在 C + + 中,声明时不能直接初始化任何变量。 为此,我们必须使用构造函数的概念。
看这个例子:-

#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;
}

希望对你有帮助!