[英]Defining the size of a vector inside a class in C++
I have a class named "Circle" which is defined by the number of points on its circumference. 我有一个名为“圆圈”的类,它由圆周上的点数定义。 Each point, in turn, is defined by its x and y value.
反过来,每个点由其x和y值定义。 In order to create individual points, I have a class like this:
为了创建单个点,我有一个这样的类:
class Point{
public:
double x; // x position
double y; // y position
// Default constructor
Point()
: x(0.0),y(0.0){
}
};
which basically creates a point. 这基本上创造了一个点。 I create the "Circle" from these points by way of this class:
我通过这个类从这些点创建“圆圈”:
class Circle{
public:
vector<Point> points; // points with x and y coordinates
// Default constructor
Circle()
: points(0.0) {
}
};
which creates the circle as a combination of points. 它将圆圈创建为点的组合。
The number of circles and the corresponding points on each of them are already pre-determined. 圆圈的数量和每个圆圈上的相应点已经预先确定。 Let's say there are M circles and N points on each of them, for the sake of argument.
为了论证,让我们说每个都有M个圆圈和N个点。 So I create these entities like this:
所以我创建这样的实体:
vector<Circle> circles(M);
and this is where my problem begins, because I want to pre-determine the size of the vector "points" for each of my "circles" objects like: 这就是我的问题开始的地方,因为我想预先确定每个“圆圈”对象的矢量“点”的大小,如:
vector<Point> points(N);
tl;dr How can I define the size of a vector inside of a class? tl; dr如何在类中定义向量的大小? It really doesn't matter whether I do it from inside of the class or not.
无论我是否从班级内部做到这一点都无关紧要。 All I want is to be able to determine the size of "points" vector for each "circles" object to N.
我想要的是能够确定每个“圆圈”对象的“点”向量的大小为N.
Define the constructor of class Circle with a parameter 使用参数定义Circle类的构造函数
class Circle{
public:
vector<Point> points; // points with x and y coordinates
// Default constructor
Circle( size_t n ) : points( n )
{
}
};
And then declare the vector of Circle 然后声明Circle的向量
vector<Circle> circles( M, N );
If you want that the constructor would be explicit as for example 如果你想要构造函数是明确的,例如
explicit Circle( size_t n ) : points( n )
{
}
then you have to define the vector the following way 那么你必须按以下方式定义矢量
vector<Circle> circles( M, Circle( N ) );
Also you can make the constructor default 您也可以将构造函数设置为默认值
Circle( size_t n = 0 ) : points( n )
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.