c++ - 运算符重载错误

标签 c++ operator-overloading

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

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

这用于在屏幕上打印。

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/

相关文章:

c++ - 如何最好地重载运算符 < > <= >= 但只写一两个比较函数?

C++:运算符重载:类内和类外。预自增运算符的歧义

c++ - 如何将初始化的结构放入结构中?

c++ - 返回变量绝对值最大值的实际值

c++ - 矩阵运算符重载不起作用

c++ - 链表运算符重载问题

C++ 将对数组的引用传递给函数

java - 将日期格式从 Java 移植到 C++

c++ - 在哪里可以获得有关 ODBC 和 Access 数据库的高质量信息?

c++ - 重载组合运算符(+ =,-=,* =和/=)。不计算应如何