c++ - 声明和定义类静态成员变量不会导致多次声明,这是为什么呢?
问题描述
我想知道为什么声明一个静态变量然后在源文件中定义它不会导致多重声明编译器错误。下面是我的意思的一个简单的例子。
// header.hpp
class Foo
{
public:
static int my_var; // declare
};
// source.cpp
#include "header.hpp"
int Foo::my_var = 5; // define
为什么 my_var 不会导致多重声明编译器错误?
另外,下面的示例代码是否会由于与上述相同的原因而导致错误?
// Class.hpp
class Foo
{
...
};
#include "Class.hpp"
class Foo; // Forward declare, no multiple declaration?
提前致谢。
解决方案
正如你所指出的,
static int my_var; // declare
是一个声明。它是static
类的成员变量的声明。
和
int Foo::my_var = 5; // define
static
是类的成员变量的定义。没有理由应该是错误。
至于
class Foo
{
...
};
#include "Class.hpp"
class Foo;
那很好。
您可以声明一个名称,在这种情况下是一个类,只要没有冲突,您可以随意多次声明。
该语言对于声明非常灵活。
您可以使用:
class Foo { ... };
class Foo;
class Foo;
class Foo;
class Foo;
class Foo;
class Foo;
class Foo;
没有任何问题。
你甚至可以使用:
class Foo { ... };
int Foo;
只要您小心使用Foo
和class
变量Foo
。
int main()
{
class Foo f1; // OK. f1 is of type class Foo
Foo = 10; // OK. Foo is the variable.
Foo f2; // Not OK. Foo is the variable not the class
}
推荐阅读
- java - 具有不同类作为锁的同步块
- reactjs - 升级到 React 16 后 componentDidUpdate 在调用 redux-form action creator 时导致无限循环
- java - Bouncy Castle ECC 密钥对生成为 EC 公钥点的坐标产生不同大小
- c - 带参数的 HTTP POST 并返回状态码
- mysql - 成功认证后不保存快速会话
- python - 无法使用 Python 3.6 安装 py7zlib 包
- java - 无法将 xml 字符串解组为 java 对象
- apache-kafka - 消费者存在于不同的服务器中
- authentication - Auth0 的主要目的是对您的应用隐藏身份提供者的实现吗?
- polymer-3.x - 在 Polymer 3 中的组件之间传递数据