类中仿函数调用的注意事项

文章讲述了C++中如何通过类名来区分具有相同名称和参数列表的函数,确保函数调用的正确性。编译器根据函数所属的类和调用上下文来决定调用哪个函数。
摘要由CSDN通过智能技术生成

在C++中,函数的完整名称由类名、函数名称和参数列表组成。因此,即使两个函数具有相同的函数名称和参数列表,只要它们属于不同的类,它们仍然被视为不同的函数。

例如,假设有两个类 ClassAClassB,分别定义了以下函数:

class ClassA {
public:
    Eigen::Vector2d operator()(double s, int n = 0);
};

class ClassB {
public:
    double operator()(double x, int dd = 0) const;
};

在这种情况下,由于 operator() 函数分别属于 ClassAClassB,它们可以在同一个命名空间下共存,不会发生冲突。

通过使用类名来区分函数,编译器可以正确地将函数调用与相应的类和函数进行匹配。例如:

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) 函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值