c++ - 函数必须只有一个参数
问题描述
我很久没有用 C++ 编码了,我正在尝试修复一些旧代码。
我收到错误:
TOutputFile& TOutputFile::operator<<(TOutputFile&, T)' must have exactly one argument
在以下代码上:
template<class T>
TOutputFile &operator<<(TOutputFile &OutFile, T& a);
class TOutputFile : public Tiofile{
public:
TOutputFile (std::string AFileName);
~TOutputFile (void) {delete FFileID;}
//close file
void close (void) {
if (isopened()) {
FFileID->close();
Tiofile::close();
}
}
//open file
void open (void) {
if (!isopened()) {
FFileID->open(FFileName, std::ios::out);
Tiofile::open();
}
}
template<class T>
TOutputFile &operator<<(TOutputFile &OutFile, const T a){
*OutFile.FFileID<<a;
return OutFile;
}
protected:
void writevalues (Array<TSequence*> &Flds);
private:
std::ofstream * FFileID;
};
该运算符重载有什么问题?
解决方案
检查参考
以 or作为左参数的
operator>>
and的重载称为插入和提取运算符。由于它们将用户定义的类型作为正确的参数(a@b 中的 b),因此它们必须实现为 non-members。operator<<
std::istream&
std::ostream&
因此,它们必须是非成员函数,并且当它们是流操作符时,它们恰好需要两个参数。
如果您正在开发自己的流类,则可以operator<<
使用单个参数作为成员函数进行重载。在这种情况下,实现看起来像这样:
template<class T>
TOutputFile &operator<<(const T& a) {
// do what needs to be done
return *this; // note that `*this` is the TOutputFile object as the lefthand side of <<
}
推荐阅读
- document.write - 我在文件 .write 中加载一个简单的 .js 文件时发现错误?
- android - 播放 MediaStore.Audio.Media 条目
- php - Phalcon:将输出渲染到变量在产品服务器中返回空字符串
- npm - 在 Botium 中执行了所有 convo 文件之后,我在哪里可以编写自定义代码以根据测试结果执行某些操作?
- sql - 如何使用每日记录更新 SQL 表?
- python - 首次登录时不存在匹配查询
- c# - WPF 中的 ScrollBar 无法正确显示并越过 tabcontrol
- elasticsearch - 如何在 Kibana 中组合 2 个名称不同但值相同的字段
- php - PHP Floor() 函数值不正确
- raspberry-pi - hostapd.service 的作业失败,因为控制进程以错误代码退出