繁体   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