我正在研究的程序有很多适用于所有类的常量.我想制作一个头文件"Constants.h",并能够声明所有相关的常量.然后在我的其他课程中,我可以包括#include "Constants.h.
我使用#ifndef... #define ...语法使其工作正常.但是,我更喜欢使用const int...常量的形式.我不太清楚如何.
我收到以下错误:
x.h:3:13: warning: ‘int X::foo()’ used but never defined
/tmp/ccK9qSnq.o: In function `main': main.cpp:(.text+0x7): undefined reference to `X::foo()'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
在构建以下代码时:
#include "x.h"
int main()
{
X::foo();
}
Run Code Online (Sandbox Code Playgroud)
namespace X
{
static int foo();
}
Run Code Online (Sandbox Code Playgroud)
#include "x.h"
namespace X
{
int foo()
{
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
谁能解释一下原因?
直到现在我才真正尝试过.是否可以在没有类的情况下在命名空间范围内使用静态?为什么不?
namespace MyNamespace
{
static int a;
}
assign something, somewhere else....
Run Code Online (Sandbox Code Playgroud) 在这个问题中,我问为什么
//foo.h
namespace foo{
int bar;
}
Run Code Online (Sandbox Code Playgroud)
当我包含foo.h多个文件时,我给了一个链接器错误.结果我需要extern int bar;防止错误.我为什么需要extern?我不想extern在每个要在多个翻译单元中访问的命名空间中的每个变量之前键入.为什么int bar;不做我所期望的呢?为什么C++标准委员会坚持让我extern到处打字?
我在.cpp中有一个代码
namespapce A
{
namespace
{
static CMutex initMutex;
}
void init()
{
//code here
}
void uninit()
{
//code here
}
}
Run Code Online (Sandbox Code Playgroud)
如果我删除互斥锁中的静态并且是否存在静态,有什么不同?静电有什么用?
谢谢!