在我声明的标题中
#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)
谢谢
我会使用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)
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |