我不太明白在C++中使用extern
和const
关键字的背后的概念。为什么我不能使用外部常量定义数组?
我已阅读了有关该主题的一些相关问题(请参阅下面的),但到目前为止,我一直无法掌握如何将它们一起使用。
相关问题:
- How do I share a variable between source files in C? With
extern
, but how? - What is the Difference Between a Definition and a Declaration?
- What is a Translation (Compilation) Unit?
- What Exactly is the One Definition Rule in C++?
好的,采取例如以下的程序代码:
dConst.hpp
extern const int NUM_GENERATORS; // Number of generators in power plant
extern const int generatorID[NUM_GENERATORS]; // Generator ID numbers
extern const bool generatorStatus[NUM_GENERATORS]; // Generator Status
vConst.cpp
const int NUM_GENERATORS = 4; // Generators in Power Plant
const int generatorID[NUM_GENERATORS] = // Generator ID numbers
{
23, 57, 49, 106
};
const bool generatorStatus[NUM_GENERATORS] = // Production status (online?)
{
true, false, false, true
};
的main.cpp
#include <iostream>
#include "dConst.hpp"
using std::cout;
using std::cin;
using std::endl;
// ----====< M A I N >====----
int main()
{
for (int iGenerator = 0; iGenerator < NUM_GENERATORS; iGenerator++)
{
cout << "Generator ";
cout << generatorID[iGenerator];
if (generatorStatus[iGenerator])
cout << "is running." << endl;
else
cout << "is offline!" << endl;
}
cout << "Press ENTER to EXIT:";
cin.get(); // Stop
return 0;
}
我无法使用NUM_GENERATORS
来声明我的数组充满发生器ID和状态。我已经在顶部包含了外部定义:#include "dConst.hpp
。从我读过的一些StackOverflow问题(可能不够紧密),编译器和链接器应该能够找到在vConst.cpp中定义的值,并继续他们的快乐方式。
那么他们为什么不这样做呢?
所以我需要将这些常量的声明包含在* vConst.cpp *到* main.cpp *中。如果我必须在另一个源文件中使用这些相同的常量,比如* powerPlant.cpp *,那么我不会最终重新声明那些常量[One Definition Rule](http://stackoverflow.com/questions/) 4192170 /什么,恰好是一定义规则,在-C)? –