类声明或定义中的静态变量? [英] static variable in the class declaration or definition?

查看:205
本文介绍了类声明或定义中的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++不熟悉。

我有一个像这样的课程:

I am new to C++.
I have a class like this:

class CodeTest
{
private:
    static const int TOTAL=100;
};

总计声明定义

当我阅读Scott Meyer的书时,提到在实现文件中我们需要定义一些内容像这样:

When I was reading Scott Meyer's book, it was mentioned that in the implementation file we need to define something like:

const int CodeTest::TOTAL;

为什么要这样做?

推荐答案

在标头之外的实现文件 中需要声明,因为否则包含该标头的每个翻译单元都将定义自己的对象(即,它自己的存储对象

The declaration in an implementation file outside of the header is required because otherwise every translation unit that includes this header would define its own object (that is, its own storage for the variable).

这将违反一个定义规则。结果将是例如如果在一个翻译单位中更改了该变量,则此更改将对其他翻译单位不可见。现在,这无关紧要,因为变量是常量。但是,使用其地址也会在不同的翻译单元中产生不同的指针。

This would violate the One Definition Rule. A consequence would be e.g. that if the variable was changed in one translation unit, this change would be invisible to other translation units. Now, this isn’t that relevant since the variable is constant. However, taking its address would also yield different pointers in different translation units.

这篇关于类声明或定义中的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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