【问题标题】:Operator Overloading in C++ return [closed]C ++中的运算符重载返回[关闭]
【发布时间】:2014-03-07 16:33:05
【问题描述】:

我是 C++ 编程新手,我想返回在运算符重载中默认传递的对象。请帮我解决这个问题.....

例如。

adi operator+(adi& s2){return s1;} 

main()
{
  s3=s1+s2;
}

【问题讨论】:

  • 不确定你到底在问什么,但你的操作员应该接受两个参数。我还建议您参考const 参考。
  • 看看this的问题。它有更多关于重载运算符的信息。
  • caebli3 的链接很好 - 具体来说,在最佳答案中查找“二进制运算符”标题。
  • 当我使用 *return 这个。我做到了。我已成功返回 s1,它被隐式传递给重载的运算符函数。

标签: c++ operators operator-overloading


【解决方案1】:

您可以将 operator+ 实现为类成员

class A {
  A operator+(const A& rhs) const {
    A result; // do something with a
    // Pick one
    return result; // returns new object
    return rhs; // returns rhs parameter
    return *this; // returns current object
  }
};

或作为非会员

A operator+(const A& a, const A& b) {
    A result; // do something with a
    return result; // returns new object
}

【讨论】:

  • 谢谢。我有了概念。我必须使用 return *this;
【解决方案2】:

如下图所示

adi operator+( const adi &s2) const
{ 
   adi temp;
/* some calculations with temp*/ 

   return temp;
} 

语义如下:您创建一个新对象,该对象将是调用运算符 this 的对象与作为参数传递给运算符的对象之和。原始对象和参数都不应更改。

运算符也可以定义为非成员函数。例如

adi operator+( const adi &s1, const adi &s2)
{ 
   adi temp;
/* some calculations with temp*/ 

   return temp;
} 

【讨论】:

  • 感谢您的帮助。但是,我明白了。我使用 return *this;返回隐式传递的 s1。
猜你喜欢
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 2014-10-16
相关资源
最近更新 更多