为什么我们必须定义一个在类中初始化的const静态成员 [英] Why we have to define a const static member that is initialized within a class

查看:126
本文介绍了为什么我们必须定义一个在类中初始化的const静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,可以在类结构中初始化积分const静态成员。这在初始化之后在类结构中使用常量时非常有用。例如,它可以用作int类型的大小数组。
查看下面的代码:

As we know,It is possible to initialize integral const static members inside the class structure.This is useful when the constant is used in the class structure after the initialization.For example,it can be used as the size of an int array. Look the code following:

class MyClass{
static const int num = 100;
int elems[num];
...
};

但是我们还必须在类定义之外定义成员 num

But we still have to define the member num outside the class definition:

const int MyClass::num;

我不知道为什么我们要这样做。
有人能告诉我为什么吗?
非常感谢。

I don't know why we have to do like this. Could someone tell me why? Thanks a lot.

此外,我写了以下代码:

In addition,I write the following code:

#include <iostream>
using namespace std;

class MyClass{
public:
MyClass()
{
    cout << "instruct class MyClass!" << endl;
}
static const int num = 100;
int elems[num];
};

//const int MyClass::num;

int main()
{
MyClass a;
const int *b = &(a.num);
cout << "&(a.num): " << &(a.num) << endl;
cout << "a.num: " << a.num << endl;
cout << "*b: " << *b << endl;
}

它在Visual Studio 2008上运行良好:

It runs well on Visual Studio 2008:

但我已经移除了在类外定义成员 的代码。

But I have removed the code that definite the member num outside the class.

我很困惑。 ?

推荐答案

类中的初始化主要用于获取常量表达式。为此,只有价值重要。一旦获取对象的地址或将其绑定到引用,编译器也需要该对象的位置。这实际上是定义提供的。

The initialization in the class is mainly used to obtain a constant expression. For this only the value matters. Once you take the address of the object or bind it to a reference, the compiler needs a location for the object as well. This is effectively what the definition provides.

这篇关于为什么我们必须定义一个在类中初始化的const静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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