C ++/Eclipse cdt,避免实现相同的功能但签名不同 [英] C++/Eclipse cdt, avoid to implement the same function but with different signature

查看:45
本文介绍了C ++/Eclipse cdt,避免实现相同的功能但签名不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know whether what I'm about to ask depends from the tool I'm using or from the language itself but anyway.

我遇到这样的情况,我用不同的签名多次声明了一个方法".如:

I have a situation where I have "one method" declared several times with different signature. Such as:

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;
};

您可以想象实现将始终相同,这只是问题的签名.有没有一种方法可以避免编写两次相同的此类函数实现?

As you can imagine the implementation would be always the same, it's just the signature the issue. Is there a way to avoid to write two times the same implementation of such functions?

一开始,我认为应该执行从类型到const类型的转换,但是显然我错了.

At the beginning I thought a casting from the type to const type would have been performed, but apparently I was wrong.

谢谢

推荐答案

  1. 您的重载未正确声明.类成员二进制运算符只能使用一个参数,另一个则隐式地 this .否则,您不能将其与中缀符号一起使用.

  1. Your overloads aren't declared properly. A class member binary operator can take only one parameter, the other is implicitly this. Otherwise you can't use it with infix notation.

您不需要两个重载.运算符不应更改操作数,因此仅使用const版本就足够了.

You don't need both overloads. The operator shouldn't change the operands, so the const version alone is enough.

所以这给我们留下了

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 重载就足够了.


As for getData(). It retunsa copy of your data, and I assume it doesn't modify the instance. Then the const overload is also enough.

这篇关于C ++/Eclipse cdt,避免实现相同的功能但签名不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆