在C++中,函数的完整名称由类名、函数名称和参数列表组成。因此,即使两个函数具有相同的函数名称和参数列表,只要它们属于不同的类,它们仍然被视为不同的函数。
例如,假设有两个类 ClassA
和 ClassB
,分别定义了以下函数:
class ClassA {
public:
Eigen::Vector2d operator()(double s, int n = 0);
};
class ClassB {
public:
double operator()(double x, int dd = 0) const;
};
在这种情况下,由于 operator()
函数分别属于 ClassA
和 ClassB
,它们可以在同一个命名空间下共存,不会发生冲突。
通过使用类名来区分函数,编译器可以正确地将函数调用与相应的类和函数进行匹配。例如:
ClassA a;
ClassB b;
Eigen::Vector2d result1 = a(1.0, 2);
double result2 = b(3.0);
在上述示例中,编译器可以根据对象的类型和函数的参数列表来选择正确的函数进行调用,而不会产生混淆。
再者,为进一步明确这一概念,对于如下代码:
class spline {
public:
double operator()(double x, int dd = 0) const;
};
class ArcSpline {
private:
spline xs_, ys_;
public:
void setWayPoints(const std::vector<double>& x_waypoints,
const std::vector<double>& y_waypoints);
double findS(const Eigen::Vector2d& p);
Eigen::Vector2d operator()(double s, int n = 0);
};
void ArcSpline::setWayPoints(const std::vector<double>& x_waypoints,
const std::vector<double>& y_waypoints) {
spline xt_, yt_;
}
inline double ArcSpline::findS(const Eigen::Vector2d& p) {
double min_s = (operator()(sL_.front()) - p).norm();
return min_s;
}
由于xs_
对象和xt_
对象都属于spline
类,因此,两者都是调用的 spline
类中的 operator()
函数; 而对于operator()(sL_.front())
,由于其隶属于 findS
函数中, 因此是表示的对当前 ArcSpline
类对象调用 operator()(double s, int n = 0)
函数。