二进制'operator':未找到采用类型为 'Fraction' 的右操作数的运算符(或者没有可接受的转换)

Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)

本文关键字:运算符 或者 操作数 可接受 转换 operator 二进制 类型 Fraction      更新时间:2023-10-16

[EDIT]我正在编写一个具有类型参数T的模板类。在该类的一个函数成员中,类型为T的变量被期望写入std::ofstream对象。在我用自定义类型参数Fraction实例化这个类之前,一切都很好。尽管我确实使operator <<过载,但还是发生了错误。

// collection.h
#include <fstream>
template<typename T>
class Collection
{
public:
    void writeToFile();
private:    
    T val;
};
template<typename T>
inline void Collection<T>::writeToFile()
{
    std::ofstream file("output.txt");
    file << val;
}
// Fraction.cpp
#include <iostream>
std::ostream& operator << (std::ostream& str, const Fraction& f)
{
    std::cout << "Hello";
    return str;
}

新答案:

您需要在Fraction.h中用这样的行声明operator <<,并在使用它的代码之前声明#include "Fraction.h"

std::ostream& operator << (std::ostream& str, const Fraction& f);

声明与定义的概念是C++(和C(的基础,所以如果你不理解区别,现在就在网上搜索一下,这样可以避免更多的困惑。

编辑:旧答案:

你确定你真的只是在做file << arr[i]而不是file << somethingElse << arr[i]吗?因为如果执行后者,则file << somethingElse的静态类型可能是std::ostream&,而不是std::ofstream&。在这种情况下,解决方案是将operator<< (..., Fraction)更改为接受(并返回(一般的std::ostream&,而不是std::ofstream&

编辑:另一种可能性是:您需要确保operator<< (..., Fraction)的声明在实例化Collection<Fraction>的位置可见(即operator<<的声明在其上方(。

相关文章: