是静态类变量与extern变量相同,只有类范围? [英] Are static class variables the same as extern variables, only with class scope?

查看:97
本文介绍了是静态类变量与extern变量相同,只有类范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,静态类变量与extern变量完全相同,因为您只需在 static int x / 中声明< extern int x 语句,实际上在其他地方定义(通常在.cpp文件中)

It seems to me that a static class variable is identical to an extern variable, because you only declare it in the static int x / extern int x statement, and actually define it elsewhere (usually in a .cpp file)

// .h file
class Foo
{
    static int x ;
} ;

// .cpp file
int MyClass::x = 0 ;



外部变量:



Extern variables:

// .h file
extern int y;

// .cpp file
int y = 1;

在这两种情况下,变量都被声明一次,并在一个文件中定义,

In both cases the variable is declared once somewhere, and defined in a file that will not be included more than once in the compilation (else linker error)

推荐答案

是的,都有静态存储持续时间和外部链接;它们本质上具有相同的运行时属性,只有(编译时)可见性不同。

Yes, both have static storage duration and external linkage; they have essentially the same run-time properties, only differing in (compile-time) visiblity.

这篇关于是静态类变量与extern变量相同,只有类范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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