如何在头文件中定义const static std :: string?

use*_*496 14 c++ static const header

我有一个类,我想std::string通过getter 存储一个真正的const或有效const 的静态.

我尝试了几种直接方法
1.

const static std::string foo = "bar";

2.

const extern std::string foo; //defined at the bottom of the header like so 
...//remaining code in header
};  //close header class declaration
std::string MyClass::foo = "bar"
/#endif // MYCLASS_H

我也试过了

3.

protected:
    static std::string foo;
public:
    static std::string getFoo() { return foo; }

这些方法分别因以下原因而失败:

  1. 错误:const string MyClass::foo非文字类型的静态数据成员的类内初始化
  2. 指定的存储类foo- 它似乎不喜欢externconst或组合static
  3. 许多'未定义的引用'由我的代码的其他部分生成的错误,甚至是getter函数的返回行

我想在头文件而不是源文件中使用声明的原因.这是一个将被扩展的类,它的所有其他函数都是纯虚拟的,所以我目前除了这些变量之外没有其他原因要有源文件.

那么怎么做呢?

小智 16

一种方法是定义一个在其中具有静态变量的方法.

例如:

class YourClass
{
public:

    // Other stuff...

    const std::string& GetString()
    {
        // Initialize the static variable
        static std::string foo("bar");
        return foo;
    }

    // Other stuff...
};
Run Code Online (Sandbox Code Playgroud)

这只会初始化静态字符串一次,每次调用该函数都会返回对该变量的常量引用.对你有用.

  • 聪明,只是为了让自己放心,我在for循环中调用了这个方法,迭代2 ^ 32次并且似乎没有内存泄漏.我喜欢billz关于将这些变量放在另一个命名空间中的观点,但最终这是我的问题的答案(我确实必须添加静态到函数声明).谢谢! (2认同)

Yu *_*Hao 13

您只能在构造函数中为整数类型而不是其他类型初始化静态const值.

将声明放在标题中:

const static std::string foo;
Run Code Online (Sandbox Code Playgroud)

并将定义放在.cpp文件中.

const std::string classname::foo = "bar";
Run Code Online (Sandbox Code Playgroud)

如果初始化在头文件中,那么包含头文件的每个文件都将具有静态成员的定义.将会出现链接器错误,因为初始化变量的代码将在多个.cpp文件中定义.