可以在C ++ Header.h文件中放置非(静态常量整型)类型

|| 我在MyClass.h文件中有一个类:
// MyClass.h
#ifndef __MY_CLASS_H__
#define __MY_CLASS_H__

#include <string>

class MyClass
{
    static const std::string MyStaticConstString; // I cannot initialize it here, because it\'s not an integral type.
};

// OK, let\'s define/initialize it out side of the class declaration
// static
const std::string MyClass::MyStaticConstString = \"Value of MyStaticConstString\";

#endif
问题是,如果该文件被包含多次,编译器将抱怨“多个定义”。 因此,我必须将ѭ1的定义移至MyClass.cpp文件。但是如果
MyClass
是库的一部分,我希望我的用户在MyClass.h文件中看到const静态值,那是有道理的,因为它是静态const值。 我应该怎么做?我希望我能说清楚。 谢谢。 彼得     
已邀请:
不,出于相同的原因,您不能将全局变量放在标头中,无论是否使用const限定符。记录您的常数(如果它是常数,那么用户为什么仍应关心它的值?)。 另外,不要在标识符前加下划线(
__MY_CLASS_H__
),它们是为实现目的保留的。     
两个问题: 像__MY_CLASS_H__这样的名称不能由您或我这样的人创建。 std :: strings不是整数类型     
没有。 你该怎么办? 在标头中执行此操作:
//myclass.h

 // MyClass.h
 #ifndef MY_CLASS_H
 #define MY_CLASS_H

class MyClass
{
    static const std::string MyStaticConstString; // I cannot initialize it here, because it\'s not an integral type.
};

extern std::string some_global_variable; //declare this with extern keyword

 #endif //MY_CLASS_H
并在源文件中执行此操作:
//myclass.cpp
#include \"myclass.h\"

const std::string MyClass::MyStaticConstString = \"Value of MyStaticConstString\";

std::string some_global_variable = \"initialization\";
请记住,带下划线前缀的名称是保留的,请勿使用。使用
MY_CLASS_H
。     

要回复问题请先登录注册