簡體   English   中英

重載插入運算符:未找到采用“ 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值,在輸出之前先進行編譯)就好了,而第二條輸出線(在這里我將date方法的返回值用作重載的插入運算符的輸入)為什么不行?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM