重载Insertion运算符:找不到哪个运算符采用'unsigned int'类型的右手操作数(或者没有可接受的转换)

时间:2015-07-24 04:05:00

标签: c++ overloading operator-keyword insertion

我正在尝试重载插入操作符。一种方法有效,另一种方法没有 - 但我不确定为什么,因为它们看起来和我一模一样。这是相关的代码(不相关的部分被删除):

#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值,berfore输出)编译得很好,但不是第二个(我使用date方法的返回值作为我重载插入操作符的输入)?

1 个答案:

答案 0 :(得分:1)

在第一行中,您可以使用monthdayyear可以转换为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);
}