操作符在C ++中重载“+”运算符 [英] Operator overloading '+' operator in C++

查看:123
本文介绍了操作符在C ++中重载“+”运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中遇到问题,该代码在Visual  Studio  2008上运行。当您有如下的重载语句时,如何为 operator + 编写函数定义?

I am facing a problem with the code below which is run on Visual Studio 2008. How do I write the function definition for operator + when you have a statement to be overloaded as follows?

class Distance
{
    private:
        int feet,inches;
};

main......

Distance Obj, Obj1(2, 2);

Obj = 3 + Obj1; // This line here

Obj1 + 3

假设我必须将值3添加到数据成员 c>

Suppose I have to add the value 3 to the data member feet of Obj1.

推荐答案

该表单的运算符将声明为:

Generally an operator of that form would be declared as:

Distance operator+(int lhs, const Distance& rhs) {
  // Assuming the int value represents feet
  return Distance(rhs.feet + lhs, rhs.inches);
}

您可能还想定义对称:

Distance operator+(const Distance& lhs, int rhs) {
  // Assuming the int value represents feet
  return Distance(lhs.feet + rhs, lhs.inches);
}

此外,我建议你听从詹姆斯·麦克内利斯的意见 - 你的工作如果您只有一个成员在一个单元中表示长度,则可以简化。

Also, I suggest you heed the advice of James McNellis--your job will be simplified if you just have one member representing lengths in a single unit.

这篇关于操作符在C ++中重载“+”运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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