c++ /Eclipse cdt,避免用不同的签名实现相同的函数

C++/Eclipse cdt, avoid to implement the same function but with different signature

本文关键字:实现 函数 Eclipse cdt c++      更新时间:2023-10-16

我不知道我要问的问题是否取决于我正在使用的工具还是语言本身,但无论如何。

我有一个情况,我有"一个方法"声明了几次不同的签名。如:

class my_class {
   public:
      int getData();
      int getData() const;
      my_class operator+(my_class&,my_class&);
      my_class operator+(const my_class&, const my_class&) const;
      //other operators, other functions etc with similar feature
   private:
      int data;
};

你可以想象实现总是相同的,这只是签名的问题。是否有一种方法可以避免为这些函数编写两次相同的实现?

开始时,我认为应该执行从类型到const类型的强制转换,但显然我错了。

谢谢

  1. 你的重载没有正确声明。类成员二元运算符只能接受一个参数,另一个是隐式的this

  2. 你不需要两个重载。操作符不应该改变操作数,因此仅使用const版本就足够了。

那么剩下的就是:

class my_class {
   public:
      int getData();
      int getData() const;
      my_class operator+(const my_class&) const;
      //other operators, other functions etc with similar feature
   private:
      int data;
};

或非成员版本:

class my_class {
   public:
      int getData();
      int getData() const;
      friend my_class operator+(const my_class&, const my_class&);
      //other operators, other functions etc with similar feature
   private:
      int data;
};
my_class operator+(const my_class&, const my_class&) {
 // code
}

对于getData()。它返回数据的副本,我假设它不会修改实例。那么const过载也足够了