我有两个不同的运算符重载。由于某种原因,它给出了错误。 如果我删除其中一个,它不会显示任何错误。我可以知道为什么吗?
我可以把两者结合起来吗?
这用于在屏幕上打印。
ostream& operator<<(ostream &out, const Point &p) {
return out << "[" << setw(4) << p.getX() << setw(1) << "," << setw(4) << p.getY() << "] " << setprecision(3) << p.getScalarValue() << endl;
}
这用于在文本文件上打印。
ofstream& operator<<(ofstream &out, const Point2D &p){
return out << "[" << setw(4) << p.getX() << setw(1) << "," << setw(4) << p.getY() << "] " << setprecision(3) << p.getScalarValue() << endl;
}
错误:
Point.cpp:91:147: error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::basic_ostream::__ostream_type {aka std::basic_ostream}’
最佳答案
您不需要第二个版本。您可以使用第一个:
Point p;
std::ofstream pointsFile("points.txt");
pointsFile << p << "\n";
首先,std::ostream& operator<<
适用于写入文件以及写入标准输出或 stderrt
其次,假设Poind2D
继承自 Point
, 通过 Point2D
到接受 Point
的函数或运算符引用也可以。
关于c++ - 运算符重载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13381712/