[英]binary '[': no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion)
[英]Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)
[编辑]我正在写一个类型为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&
。
编辑:另一种可能性:您需要确保从实例化Collection<Fraction>
的位置可以看到operator<< (..., Fraction)
的声明(即, operator<<
的声明在其上方)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.