首页 > 解决方案 > 声明和定义类静态成员变量不会导致多次声明,这是为什么呢?

问题描述

我想知道为什么声明一个静态变量然后在源文件中定义它不会导致多重声明编译器错误。下面是我的意思的一个简单的例子。

// 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?

提前致谢。

标签: c++

解决方案


正如你所指出的,

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;

只要您小心使用Fooclass变量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
}

推荐阅读