我已经很长时间没有用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;
};
该运算符重载有什么问题?
答案 0 :(得分:5)
operator>>
和operator<<
的重载占用std::istream&
或std::ostream&
作为左手参数称为插入和 提取运算符。由于它们采用用户定义的类型作为 正确的参数(a @ b中的b),必须将其实现为非成员。
因此,它们必须是非成员函数,并且在它们打算成为流运算符时正好采用两个参数。
如果您正在开发自己的流类,则可以使用单个参数作为成员函数重载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 <<
}
答案 1 :(得分:0)
被定义为成员函数的运算符重载函数仅接受一个参数。如果<<
运算符重载,则需要多个参数。将其设置为friend
函数可以解决此问题。
class {
...
friend TOutputFile &operator<<(TOutputFile &OutFile, const T &a);
...
};
template<class T>
TOutputFile &operator<<(TOutputFile &OutFile, const T &a) {
*OutFile.FFileID << a;
return OutFile;
}
标记为friend
的函数将允许该函数访问与其成为朋友的类的私有成员。