2017-07-23 70 views
-1

我正在嘗試爲某些給定的點創建Voronoi圖。每個點都有不同的屬性,我想將其表示爲顏色。爲了用Boost Point概念映射我自己的Point結構,我寫了一些代碼。我有以下設置:其他結構中的結構構造函數

struct Point { 
    double a; 
    double b; 
    Point(double x, double y) : a(x), b(y) {} 
}; 

// This Point structure is mapped to Boost Point concept. Code emitted 

我有另一種結構:

struct Point_Collection { 
    Point xy(double x, double y); 
    short color; 

}; 

Visual Studio創建一個自動定義爲:

Point Point_Collection::xy(double x, double y) 
{ 
    return Point(); 
} 

現在,如果我嘗試實例化對象Point_collection爲:

std::vector<Point_Collection> *test; 
test = new std::vector<Point_Collection>(); 

Point_Collection xy_color; 

for (int i = 0; i < 5000; i++) { 
    xy_color.xy(rand() % 1000, rand() % 1000); 
    xy_color.color = rand() % 17; 
    test->push_back(xy_color); 
} 

我收到一個錯誤。

error C2512: 'Point': no appropriate default constructor available 

有人可以指出我爲什麼會發生這種情況嗎?

+0

你得到了什麼錯誤? – MKR

+1

Point xy(double x,double y)的用途是什麼;'作爲'Point_Collection'成員的一部分的聲明是什麼?爲什麼不能只聲明'Point xy'。 – MKR

+0

'xy'是一個成員函數,你必須寫'xy_color.xy(.....);'。並提供函數的主體 –

回答

3

Point xy(double x, double y);聲明瞭一個成員函數Point_Collectionxy識別,接受兩個雙打和由值返回Point對象。

如果你想要一個簡單的彙總保存一個點,C++ 11及以後的方法是將它定義成這樣:

struct Point_Collection { 
    Point xy; 
    short color; 
}; 

Point_Collection xy_color{ { rand()%100, rand()%100 }, static_cast<short>(rand()%16)}; 

以上是使用值初始化語法的簡單集合初始化。您應該更喜歡它,原因有兩個:

  1. 它不會縮小轉換範圍。 (其中intshort是,因此演員)。
  2. 這很容易實現。如果您的班級擁有所有公共成員,則無需打字。

(也rand在C++ 11更好的選擇,檢查出頭部<random>


如果您沒有訪問C++ 11,那麼你可以寫一個構造函數爲Point_Collection

struct Point_Collection { 
    Point xy; 
    short color; 

    Point_Collection(Point xy, short color) 
    : xy(xy), color(color) {} 
}; 

Point_Collection xy_color (Point(...,...), ...); 

或者使用具有更多詳細的語法集合初始化:

struct Point_Collection { 
    Point xy; 
    short color; 
}; 

Point_Collection xy_color = { Point(rand()%100, rand()%100), rand()%16 }; 

(由於上述是C++ 03,rand()%16將被默默地轉換爲short,儘管它是狹窄)。

+0

你可以請我建議一個資源,我可以閱讀這樣的關於C++的信息。另外,坦率地說,我不明白我的Point結構到Boost Point概念的映射,我只是從Boost文檔複製粘貼,它工作。我可以在哪裏學習這些基礎知識? –

+0

@MojoJojo - 學習C++的正確方法是從[良好的審查,書](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – StoryTeller

+0

謝謝,只是通過該線程。似乎我有很多要學習。再次感謝。 –