[英]Overloading Insertion Operator: no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion)
I'm trying to overload the Insertion Operator. 我正在尝试重载插入运算符。 One method works, the other does not - but I'm not sure why, as they seem identical to me.
一种方法行之有效,另一种则行不通-但我不确定为什么,因为它们似乎与我相同。 Here's the relevant code (irrelevant sections chopped out):
以下是相关代码(切掉了不相关的部分):
#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());
So why does the first output line (where I get the UINT values first, berfore outputting) compile just fine, but not the second (where I use the return values of the date methods as input to my overloaded insertion operator)? 那么,为什么第一条输出线(在输出之前先获得UINT值,在输出之前先进行编译)就好了,而第二条输出线(在这里我将date方法的返回值用作重载的插入运算符的输入)为什么不行?
In the first line, you are able use month
, day
, and year
can be converted to INT&
. 在第一行中,您可以使用可以将
month
, day
和year
转换为INT&
。
In the second line, you are using the return values of the member functions. 在第二行中,您正在使用成员函数的返回值。 They are temporary objects.
它们是临时对象。 They cannot be bound to
INT&
. 它们不能绑定到
INT&
。
In order to be able to use, 为了能够使用,
bfw << (m_Game_Date.Month()) << (m_Game_Date.Day()) << (m_Game_Date.Year());
The second argument of the operator<<
function must be a T1 const&
, not T1&
. 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.