二元'运算符':没有找到哪个运算符采用'分数'类型的右手操作数(或者没有可接受的转换)

时间:2016-11-07 17:17:12

标签: c++ templates

[编辑] 我正在编写一个类型参数为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;
}

1 个答案:

答案 0 :(得分:2)

新答案:

您回答需要在使用该代码的代码之前在operator <<Fraction.h中使用这样的行声明#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<<的声明在其上方)。