![](/img/trans.png)
[英]Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)
[英]Overloading Insertion Operator: no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion)
我正在尝试重载插入运算符。 一种方法行之有效,另一种则行不通-但我不确定为什么,因为它们似乎与我相同。 以下是相关代码(切掉了不相关的部分):
#include <string>
#include <fstream>
#define UINT unsigned int
///////////////////////////////////////////////////////////
class Date
{
public:
// These just return unsigned ints
UINT Month();
UINT Day();
UINT Year();
UINT month;
UINT day;
UINT year;
};
///////////////////////////////////////////////////////////
class BinaryFileWriter
{
public:
virtual bool Open(string i_Filename);
void Write(UINT i_Uint);
private:
ofstream ofs;
};
template <typename T1>
BinaryFileWriter& operator << (BinaryFileWriter& i_Writer, T1& i_Value)
{
i_Writer.Write(i_Value);
return(i_Writer);
}
bool BinaryFileWriter::Open(string i_Filename)
{
ofs.open(i_Filename, ios_base::binary);
}
void BinaryFileWriter::Write(UINT i_Uint)
{
ofs.write(reinterpret_cast<const char*>(&i_Uint), sizeof(UINT));
}
///////////////////////////////////////////////////////////
void Some_Function(Date i_Game_Date)
{
BinaryFileWriter bfw;
bfw.Open("test1.txt");
// This works
UINT month = i_Game_Date.Month();
UINT day = i_Game_Date.Day();
UINT year = i_Game_Date.Year();
bfw << month << day << year;
// This does not - gives me error 'error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion) '
bfw << (m_Game_Date.Month()) << (m_Game_Date.Day()) << (m_Game_Date.Year());
那么,为什么第一条输出线(在输出之前先获得UINT值,在输出之前先进行编译)就好了,而第二条输出线(在这里我将date方法的返回值用作重载的插入运算符的输入)为什么不行?
在第一行中,您可以使用可以将month
, day
和year
转换为INT&
。
在第二行中,您正在使用成员函数的返回值。 它们是临时对象。 它们不能绑定到INT&
。
为了能够使用,
bfw << (m_Game_Date.Month()) << (m_Game_Date.Day()) << (m_Game_Date.Year());
operator<<
函数的第二个参数必须是T1 const&
,而不是T1&
。
template <typename T1>
BinaryFileWriter& operator << (BinaryFileWriter& i_Writer, T1 const& i_Value)
{
i_Writer.Write(i_Value);
return(i_Writer);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.