C++ How to share constants with extern between cpp - Error: storage class specified

C++ How to share constants with extern between cpp - Error: storage class specified

我有头文件,其中我用 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

然后在源代码中我这样定义它们:

#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' 指定的存储 class?

首先,这些似乎不是 class 成员。您使用 extern 的方式看起来像是您打算让这些免费。也许在命名空间中。将它们从 class.

中取出

然后,当您定义它们时,省略 extern

在此上下文中,它表示 "find this variable elsewhere"。你不想在别处找到它。 这里

// 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 对象定义执行相同的操作!

我认为您要么想在 class 中使用静态成员,要么使用命名空间而不是 class,要么将您的常量放在全局命名空间中。

对于静态成员:

class Constants
{
    public:
        Constants(){}
        static const std::string DELIMITER;
        static const std::string FILENAME;
        static const int BLUCAR;
        static const int REDCAR;
        static const int EMPTY;
        static const int SPARSE_LIM;
    protected:
    private:
};

并在您的源文件中

const std::string Constants::DELIMITER = ",";
const std::string Constants::FILENAME = "cars.csv";
const int Constants::BLUCAR = 1;
const int Constants::REDCAR = 2;
const int Constants::EMPTY = 0;
const int Constants::SPARSE_LIM = 5;

但是,看起来您的 class 更像是一个命名空间而不是 class,因为创建实例没有意义。

但还有另一种选择。您甚至可能不想使用 class 或命名空间,而只是将它们全部放在全局命名空间中:

// header
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
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;