2011-05-23 17 views
2

我有MyClass.h文件中的類:是有可能把非(靜態常量積分)類型在C++ Header.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 

的問題是,編譯器會抱怨「多重定義」如果該文件包含多次。

所以我必須將MyStaticConstString的定義移動到MyClass.cpp文件。但是如果MyClass是庫的一部分,我希望我的用戶在MyClass.h文件中查看const靜態值,這是合理的,因爲它是一個靜態常量值。

我該怎麼辦?我希望我明確自己。

謝謝。

彼得

+0

在C#中,您始終可以將類初始化放在類聲明中。 – 2011-05-23 22:33:00

+0

@Neil,我的意思是C++成員初始化規則真的令人沮喪,我個人認爲。我沒有從這些規則中受益。讓我知道他們是否有。 – 2011-05-24 21:07:02

回答

1

沒有,出於同樣的原因,你不能把全局變量在頭文件中,常量,合格與否。記錄你的常量(如果它是一個常量,那麼用戶爲什麼要關心它的價值呢?)。

另外,不要用下劃線(__MY_CLASS_H__)預先標記您的標識符,它們保留用於實現的東西。

+0

是的,有可能是std或boost的人使用'__THIS_STYLE_H__'指南。嗯,我會將它重命名爲「THIS_STYLE_H」。 – 2011-05-23 22:48:32

+0

@Peter如果助力球員這樣做(我懷疑),那麼他們做錯了。這些名稱是爲實現保留的,特別是針對特定編譯器的std :: namespace。 – 2011-05-23 23:09:59

1

兩個問題:

  • 的名字,像__MY_CLASS_H__不能由您或我創建。

  • 的std ::字符串不是整型

1

你應該怎麼做?

在包頭這樣做:

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

+0

感謝您的回覆。是的,這就是我正在做的。但是如果MyClass是庫的一部分,並且我希望我的用戶在MyClass.h文件中看到常量靜態值,這是合理的,因爲它是一個靜態常量值。 (正如Cat ++所指出的,我們應該把它放在文檔中) – 2011-05-24 21:05:07

相關問題