使用初始化列表之前的C++数据验证

C++ Data validation before using initialization list

本文关键字:C++ 数据 验证 初始化 列表      更新时间:2024-05-10

我正在实现一个Triangle类,它的属性是Point类的三个私有对象。到目前为止,我正在三角形构造函数中使用一个初始化器列表来初始化这三个点。问题是,在创建它的时候,我必须确定它是否是一个有效的三角形(检查两边的和是否大于第三个(。我如何验证这一点?注意:我可以把我的三角构造函数改成这样:

Triangle(x0, y0, x1, y1, x2, y2)

但如果它看起来像这样,我真的很想知道该怎么做:

Triangle(p1, p2, p3)

我的代码看起来像这个

class Point {
private:
double x; 
double y;
public:
Point():x(0.0), y(0.0) {};
Point(double x0, double y0):x(x0), y(y0){};
double distance(Point p) {//distance between two points};
//getters
//setters
};
class Triangle {
private:
Point v1;
Point v2;
Point v3;
public:
Triangle(Point p1, Point p2, Point p3): 
v1(p1.getX(), p1.getY()),
v2(p2.getX(), p2.getY()),
v3(p3.getX(), p3.getY())  {
//Edit
if v1.distance(v2) + v2.distance(v3) <= v1.distance(v3) {
//This is not a valid triangle, assign correct values to
//v1, v2 and v3
}
}
//Other methods.
};   

通过构造检查并仅创建有效对象在c++中非常常见。甚至有一个关于它的核心准则;如果构造函数无法构造有效对象,则引发异常。

所以在你的情况下,你可以提供这样的东西:

bool is_valid_triangle(Point p1, Point p2, Point p3) {
...  // Implementation
}
...

Triangle::Triangle(Point p1, Point p2, Point p3) :
v1{p1}, // requires copy constructor for Point which you should add
v2{p2}, v3{p3}
{
if (!is_valid_triangle(p1, p2, p3)) {
throw std::invalid_argument("Points provided are not a triangle");
}
... // Set up class
}

然后用户需要检查他们是否正在创建有效的三角形:

try {
Triangle t{p1, p2, p3};
... // operate with t
} catch(...) {
... // Warn the user
}