簡體   English   中英

+ 運算符的運算符重載 C++

[英]Operator Overloading C++ for + operator

我目前正在學習如何在 C++ 中進行運算符重載,我在網上找到了一些在下面運行時可以工作的代碼。

class Complex {
 private:
  int real, imag;

 public:
  Complex(int r = 0, int i = 0) {
    real = r;
    imag = i;
  }

  // This is automatically called when '+' is used with
  // between two Complex objects
  Complex operator+(Complex const &obj) {
    Complex res;
    res.real = real + obj.real;
    res.imag = imag + obj.imag;
    return res;
  }
  void print() { cout << real << " + i" << imag << endl; }
};

int main() {
  Complex c1(10, 5), c2(2, 4);
  Complex c3 = c1 + c2;  // An example call to "operator+"
  c3.print();
}

但是,當我嘗試類似的結構時,收到以下錯誤:未找到默認構造函數和 << 我不熟悉的錯誤。

class Chicken {
 private:
  int i;
  int k;
  int s;
  int total = 0;

 public:
  Chicken(int index, int kentucky, int sign) {
    i = index;
    k = kentucky;
    s = sign;
  }
  Chicken operator+(Chicken obj) {
    Chicken Chicky;
    Chicky.total = i + obj.i;
    return Chicky;
  }
};

int main() {
  Chicken P(1, 2, 3);
  Chicken U(2, 2, 2);
  Chicken W = P + U;

  cout << W;
}

在此處輸入圖片說明

下面是更正后的例子。 首先,您收到錯誤是因為在operator+內部,您默認構造了一個 Chicken 類型的對象,但您的類沒有任何默認構造函數。 解決方案是添加默認構造函數。

#include <iostream>
class Chicken{
    //needed for cout<<W; to work
    friend std::ostream& operator<<(std::ostream& os, const Chicken &rhs);
    private:
      int i = 0;
      int k = 0;
      int s = 0;
      int total = 0; 

    public:

    

    //default constructor 
    Chicken() = default;
    
    
    //use constructor initializer list instead of assigning inside the body
    Chicken(int index, int kentucky, int sign): i(index), k(kentucky), s(sign){

        //i = index;
        //k = kentucky;
        //s = sign;
    }
    Chicken operator + (Chicken obj){
        Chicken Chicky;//this needs/uses default constructor
        Chicky.total = i + obj.i;
        return Chicky;
    }
   
};
std::ostream& operator<<(std::ostream& os, const Chicken &rhs)
{
    os << rhs.i << rhs.k << rhs.s << rhs.total ;
    return os;
}
int main(){
    
   
    
    Chicken P(1,2,3); //this uses parameterized constructor
    Chicken U(2,2,2); //this uses parameterized constructor
    Chicken W = P+U;  //this uses overloaded operator+
    
    std::cout << W;   //this uses oveloaded operator<<
    
}
 

其次,您使用了語句cout<<W; 但沒有重載operator<< 對於std::cout<< W; 要工作,您需要重載operator<<如我在上面的代碼中所示。

您可以在此處查看工作示例。

第三,您可以/應該使用構造函數初始值設定項列表,而不是在構造函數體內分配值,如上所示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM