簡體   English   中英

重載 = 運算符

[英]Overloading = operator

我編寫了以下測試程序:

 int main(int argc, char** argv)
   {

    ifstream inFile;
    inFile.open("D:\\C++\\Assignments\\in1.txt");
    if (!inFile) {
            cout << "Unable to open file";
            exit(1); // terminate with error
    }
    Complex a,b,c;
    inFile >> a;
    inFile >> b;
    ofstream out;
    out.open("D:\\C++\\Assignments\\out1.txt");
    out << a <<endl<< b<<endl;  // dumps data to a stream connected to a file
    out << c=a <<endl;
    out.close();



  return 0;
  }

我已經重載 = 如下:

  void Complex::operator=(const Complex &a)//mulptiplication
  {
    real=a.real;
    imag=a.imag;
   }

但是我收到了類似的錯誤:與操作符<<不匹配。 任何人都可以幫助解決錯誤嗎?

這是你的問題:

out << c=a <<endl;

您需要返回一個 Complex&

嘗試這個:

Complex& Complex::operator=(const Complex &a)//mulptiplication
{
  real=a.real;
  imag=a.imag;

  return *this;
}

原因是 c=a 產生一個 void 並且沒有操作符<<適用於左側的 void

為了清楚起見,您可以重寫為:

c = a;
out << c << endl;

ortang 也是對的,Complex 類必須有一個 operator<<。

問題在於out << a << endl << b << endl ,因為我猜您沒有為Complex類重載operator<<

看看這個 SO post如何重載operator<<

如果realimag本身是具有正確賦值語義的類型(例如像intdouble這樣的原始類型),那么實現自己的operator=多余且容易出錯的 只需使用編譯器生成的一個。

即使有適當的操作員

out << c=a <<endl;

被解析為

(out << c) = (a <<endl);

由於運算符優先級,會發生錯誤。

暫無
暫無

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

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