0

我有两个不同的运算符重载。由于某种原因,它给出了错误。如果我删除其中一个,则它不会显示任何错误。我可以知道为什么吗?

我可以将两者结合起来吗?

这用于在屏幕上打印。

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:错误:从类型“std::basic_ostream::__ostream_type {aka std::basic_ostream}”的表达式中对类型“std::ofstream& {aka std::basic_ofstream&}”的引用无效初始化< /p>

4

1 回答 1

3

您不需要第二个版本。您可以使用第一个:

Point p;
std::ofstream pointsFile("points.txt");
pointsFile << p << "\n";

首先,std::ostream& operator<<写入文件以及写入标准输出或 stderrt 的工作

其次,假设Poind2D继承自Point,将 a 传递给接受引用Point2D的函数或运算符也可以。Point

于 2012-11-14T15:26:31.200 回答