[英]Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)
[EDIT] I am writing a template class with type argument T
. [编辑]我正在写一个类型为
T
的模板类。 In one of the functions member of that class, a variable with type T
is expected to be written to a std::ofstream
object. 在该类的函数成员之一中,类型
T
的变量应写入std::ofstream
对象。 Everything is fine until I instantiate this class with a custom type argument Fraction
. 一切正常,直到我使用自定义类型参数
Fraction
实例化此类。 The error occurs although I did overload the operator <<
. 尽管我确实重载了
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;
}
New answer: 新答案:
You answer need to declare operator <<
with a line like this in Fraction.h
, and #include "Fraction.h"
before the code that uses it: 您回答需要在
Fraction.h
中用这样的一行声明operator <<
,并在使用它的代码之前#include "Fraction.h"
:
std::ostream& operator << (std::ostream& str, const Fraction& f);
The concept of declarations vs definitions is fundamental to C++ (and C), so if you don't understand the distinction, search the web about it now to save yourself any more confusion. 声明与定义的概念是C ++(和C)的基础,因此,如果您不了解该区别,请立即在网上搜索有关它的信息,以免进一步混淆。
Edit: Old answer: 编辑: 旧答案:
Are you sure that you are really just doing file << arr[i]
and not file << somethingElse << arr[i]
? 您确定您确实在执行
file << arr[i]
而不是file << somethingElse << arr[i]
吗? Because if you do the latter, then the static type of file << somethingElse
is likely to be std::ostream&
rather than std::ofstream&
. 因为如果执行后者,则
file << somethingElse
的静态类型很可能是std::ostream&
而不是std::ofstream&
。 In that case, the solution is to change operator<< (..., Fraction)
to accept (and return) a general std::ostream&
rather than std::ofstream&
. 在这种情况下,解决方案是将
operator<< (..., Fraction)
更改为接受(并返回)常规std::ostream&
而不是std::ofstream&
。
Edit: Another possibility: you need to make sure the declaration of operator<< (..., Fraction)
is visible from the place you instantiate Collection<Fraction>
(ie the declaraction of operator<<
is above it). 编辑:另一种可能性:您需要确保从实例化
Collection<Fraction>
的位置可以看到operator<< (..., Fraction)
的声明(即, operator<<
的声明在其上方)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.