簡體   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