gpt4 book ai didi

c++ - 重载插入运算符 : no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion)

转载 作者:行者123 更新时间:2023-11-30 05:40:30 25 4
gpt4 key购买 nike

我正在尝试使插入运算符过载。一种方法有效,另一种方法无效 - 但我不确定为什么,因为它们看起来与我相同。这是相关代码(不相关的部分被切掉):

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

最佳答案

在第一行,你可以使用month , day , 和 year可以转换为INT& .

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

关于c++ - 重载插入运算符 : no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31601987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com