2016-11-07 61 views
0

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

请**用[mcve]或[SSCCE(Short,Self Contained,Correct Example)](http://sscce.org)您的问题 – NathanOliver

回答

2

新的答案:

你回答需要用Fraction.h这样一行来声明operator <<,并且#include "Fraction.h"使用它的代码之前:

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

声明的概念vs定义是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<<的声明高于它)可见。

+1

您真的应该等待OP提供一个[mcve]。现在这些只是猜测。 – NathanOliver

+0

@NathanOliver:我可以猜想,如果我想!这只是我选择浪费的时间。 –

+0

我刚刚编辑了这个问题,使其更清晰,更精确。 – Rickie