繁体   English   中英

C ++通用运算符重载

[英]c++ generic operator overload

如何使用运算符重载来添加两个对象而又不使其成为任何对象的成员? 这与插入运算符重载有关吗?

所以代替这个,使用更通用的东西,即与任何对象一起使用?:

sameObjectType operator + ( const sameObjectType  &x,  const sameObjectType &y ) {
    sameObjectType z;
    z = x+y;

    return z;
}

// I want to do the same for subtraction operatoR

sameObjectType operator - ( const sameObjectType  &x,  const sameObjectType &y ) {
    sameObjectType z;
    z = x-y;

    return z;
}

您可以从此示例代码中获得想法。

#include <iostream>
class One {
private:
 int num1, num2;

public:
  One(int num1, int num2) : num1(num1), num2(num2) {}
  One& operator += (const One&);
  friend bool operator==(const One&, const One&);
  friend std::ostream& operator<<(std::ostream&, const One&);
};

std::ostream&
 operator<<(std::ostream& os, const One& rhs) {
   return os << "(" << rhs.num1 << "@" << rhs.num2 << ")";
 }

One& One::operator+=(const One& rhs) {
  num1 += rhs.num1;
  num2 += rhs.num2;
  return *this;
}

One operator+(One lhs, const One &rhs)
{
 return lhs+=rhs;
}

 int main () {
 One x(1,2), z(3,4);
 std::cout << x << " + " << z << " => " << (x+z) << "\n";
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM