我已经很长时间没有用 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;
};
该运算符重载有什么问题?
最佳答案
The overloads of
operator>>
andoperator<<
that take astd::istream&
orstd::ostream&
as the left hand argument are known as insertion and extraction operators. Since they take the user-defined type as the right argument (b in a@b), they must be implemented as non-members.
因此,它们必须是非成员函数,并且当它们是流运算符时恰好采用两个参数。
如果您正在开发自己的流类,则可以重载 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 <<
}
关于c++ - 函数必须只有一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237411/