问题描述
我在头文件中用extern声明了一些常量:
I've the header file in which I declare some constants with extern:
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <string>
class Constants
{
public:
Constants(){}
extern const std::string DELIMITER;
extern const std::string FILENAME;
extern const int BLUCAR;
extern const int REDCAR;
extern const int EMPTY;
extern const int SPARSE_LIM;
protected:
private:
};
#endif // CONSTANTS_H
然后在源代码中将它们定义为
Then in the source I define them like this:
#include "constants.h"
extern const std::string DELIMITER = ",";
extern const std::string FILENAME = "cars.csv";
extern const int BLUCAR = 1;
extern const int REDCAR = 2;
extern const int EMPTY = 0;
extern const int SPARSE_LIM = 5;
编译器为什么给我错误:为 DELIMITER指定存储类?
Why the compiler gives me Error: storage class specified for 'DELIMITER'?
推荐答案
首先,这些似乎不是班级成员。您使用 extern
的方式看起来像是免费的。也许在命名空间中。
Firstly, these don't seem to be class members. The way you're using extern
it looks like you intended for these to be free. Perhaps in a namespace. Take them out of that class.
然后,在定义它们时,省去 extern
。
Then, when you define them, leave out the extern
.
在这种情况下,它的意思是在其他位置查找此变量。您不想在其他地方找到它。它在此处!
In this context it means "find this variable elsewhere". You don't want to find it elsewhere. It's here!
// Header
namespace Constants {
extern const std::string DELIMITER;
extern const std::string FILENAME;
extern const int BLUCAR;
extern const int REDCAR;
extern const int EMPTY;
extern const int SPARSE_LIM;
}
// Source
namespace Constants {
const std::string DELIMITER = ",";
const std::string FILENAME = "cars.csv";
const int BLUCAR = 1;
const int REDCAR = 2;
const int EMPTY = 0;
const int SPARSE_LIM = 5;
}
请记住,对于 static,您也可以这样做
对象定义!
Remember, you'd do the same for static
object definitions!
这篇关于C ++如何在cpp之间与extern共享常量-错误:指定了存储类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!