2016-04-21 75 views
1

我想將對象名稱保存爲字符串。我可以使用幾行代碼來解釋嗎?如何將對象名稱保存爲字符串

#include <iostream> 
#include <string> 
#include <stdio.h> 

using namespace std; 

class Example 
{ 
public: 
    string object_name; 
    //code... 
}; 

int main() 
{ 
    Example object; 
    cout<<object.object_name<<endl; //In this case the output should be "object", how to achieve this ? 
    return 0; 
} 
+2

你將它設置爲:'object.object_name =「object」;' - 我很確定這不是你想要的答案,但C++沒有那種反射/內省。 –

+2

[在運行時獲取C++對象名稱]的可能重複(http://stackoverflow.com/questions/468956/get-c-object-name-in-run-time) –

+0

也許看看[C++ reflexion]( http://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-ac-application) – steiner

回答

0

要獲得在C++這個功能,你必須設定object_name自己,要做到這一點,而不冗餘指定它爲Example實例及其object_name數據成員是使用宏來存儲的唯一途徑「串化」的標識符:

#define EXAMPLE(IDN) Example IDN{ #IDN } 

EXAMPLE(object); 

這是相當醜陋的恕我直言:人們會誤認爲它是一個運行時函數調用。

3

無法從內部對象訪問變量名稱,因爲它只存在於源代碼級別。你能做的最好的,是提供對象的構造函數的名稱:Example object("object"),你甚至可以把它包裝宏觀避免重複:

#define CREATE_OBJECT(TYPE, NAME) TYPE NAME(#NAME) 

CREATE_OBJECT(Example, object); 

您應該複製/移動物體不同,因爲它會保留名稱這可能與複製名稱不相關。您將刪除複製/移動構造函數,大大減少對象的用處,並定義新的構造函數,這些構造函數使用現有對象和新名稱,併爲其創建宏。

即便再有是引用一個問題...

TL; DR:它通常不值得。

相關問題