C++中的静态类

Pet*_*isu 4 c++ static class

在我声明的标题中

#ifndef SOUND_CORE
#define SOUND_CORE

static SoundEngine soundEngine;

...
Run Code Online (Sandbox Code Playgroud)

但SoundEngine的构造函数被多次调用,当它被声明为全局静态时,它是如何可能的

我称之为

#include "SoundCore.h"
Run Code Online (Sandbox Code Playgroud)

并直接使用它

soundEngine.foo()
Run Code Online (Sandbox Code Playgroud)

谢谢

Alo*_*ave 7

将为包含标题的每个转换单元创建在头文件中声明的静态变量的副本.
永远不要在头文件中声明静态变量.

您可以使用单个对象.


rub*_*nvb 7

我会使用extern而不是静态.这extern是为了什么.

在标题中:

extern SoundEngine soundEngine;
Run Code Online (Sandbox Code Playgroud)

在随附的源文件中:

SoundEngine soundEngine;
Run Code Online (Sandbox Code Playgroud)

这将为实例创建一个翻译单元,并且包含标题将允许您在代码中的任何位置使用它.

// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp

int foo()
{
hours = 1;
}


// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line

int main()
{
foo();
}
Run Code Online (Sandbox Code Playgroud)