我可以使用C++中的任何方法,例如重载或模板,这将允许我将类实例作为参数传递给cmath函数吗?例如,如果我有一个名为“点”(如下所示)的类,有什么方法可以执行操作std::abs(Point(-4, -9))
并使其返回Point(4, 9)
?如何在自定义类实例上执行cmath函数?
#include <iostream>
#include <cmath>
class Point{
private:
double x, y;
public:
Point(double x, double y) {
this->x = x;
this->y = y;
}
// Approach 1 that I would like to avoid
static Point abs1(const Point &p1) {
return Point(std::abs(p1.x), std::abs(p1.y));
}
// Approach 2 that I would like to avoid
Point abs2(void) {
return Point(std::abs(x), std::abs(y));
}
};
int main()
{
Point pt1(-4.0, -9.0), pt2;
pt2 = std::abs(pt1) // <-- What I would like to be able to do
pt2 = Point::abs1(point_d); // <-- Function call 1 that I would like to avoid
pt2 = point_d.abs2(); // <-- Function call 2 that I would like to avoid
return 0;
}
还是我仅限于使用需要我类为基础的方法调用Point::abs(Point(-4, -9))
或Point(-4, -9).abs()
?总而言之,我可以扩充cmath函数来接受一个类实例吗?
我看了一下,我找不到关于这个主题的任何信息,但是我对C++来说很新。所以,如果能够做到这一点,我希望得到任何信息,以及这种行为是否不明智,如果是这样,为什么?
在此先感谢。