2017-07-23 71 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

谢谢,只是通过该线程。似乎我有很多要学习。再次感谢。 –