2013-10-22 75 views
4

我需要幫助理解以及運用struct結構在C++中的結構

我有這樣的代碼片段:

struct PCD 
{ 
    PointCloud::Ptr cloud; 
    std::string f_name; 
    PCD() : cloud (new PointCloud) {}; 
}; 

但我不明白怎麼可能該行:

PCD() : cloud (new PointCloud) {}; 

或更好,它有什麼作用? A structstruct

我在哪裏可以找到一個很好的解釋呢?

+2

[成員初始化列表。](http://en.cppreference.com/w/cpp/language/initializer_list) – 0x499602D2

回答

5

cloud是指向PointCloud對象的指針。它是PCD結構的成員。當使用初始化程序列表初始化此結構時,將爲該指針分配一個新的PointCloud對象。

這在PointCloud結構/類是有可能被發現:

typedef PointCloud* Ptr; 
2

結構是一種類的,一切都是公開的。 這裏您正在尋找struct PCD的默認構造函數以及其數據成員之一的初始化。 我們不知道PointCloud是一個結構體還是一個類,但似乎PCD在該類型的實例上包含一個指針。所以默認的構造函數創建一個新的實例。

2
PCD() : cloud (new PointCloud) {}; 

這是結構PCD的默認構造函數。

:語法表示member initializer list正被用於初始化一個或多個結構數據成員。在這種情況下,指針cloud被分配一個新的動態分配的對象PointCloud

成員初始化程序列表用於初始化非靜態數據成員之前構造函數的主體被執行。它也是引用參考型成員的唯一途徑。

有關構造函數和成員初始化列表的更多信息here

3
PCD() : cloud (new PointCloud) {}; 

是一個PCD構造函數,它使用新的PointCloud實例初始化雲變量。

struct PCD 
{ 
    PointCloud::Ptr cloud; 
    std::string f_name; 
    PCD() : cloud (new PointCloud) {}; 
}; 

可以被改寫並可視化爲:

struct PCD 
{ 
public: 
    PointCloud::Ptr cloud; 
    std::string f_name; 
    PCD(); 
}; 

PCD::PCD() : cloud (new PointCloud) {};