重载插入运算符:未找到采用 'unsigned int' 类型的右手操作数的运算符(或没有可接受的转换)

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 值,然后输出)编译得很好,但第二行(我使用日期方法的 return 值作为输入我重载的插入运算符)?

第一行可以用monthdayyear可以转换成INT&

在第二行中,您使用了成员函数的 return 值。它们是临时对象。它们不能绑定到 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);
}