上QQ阅读APP看书,第一时间看更新
Converting between types
You can also perform conversions. In math, you can define a vector that represents direction, so that the line drawn between two points is a vector. In our code we have already defined a point class and a cartesian_vector class. You could decide to have a constructor that creates a vector between the origin and a point, in which case you are converting a point object to a cartesian_vector object:
class cartesian_vector
{
double x; double y;
public:
cartesian_vector(const point& p) : x(p.x), y(p.y) {}
};
There is a problem here, which we will address in a moment. The conversions can be called like this:
point p(10, 10);
cartesian_vector v1(p);
cartesian_vector v2 { p };
cartesian_vector v3 = p;