且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在过载之后没有针对std :: end1的'operator<<'的匹配

更新时间:2023-11-12 22:22:52

简单重载解释此错误。事实上, std :: cout 只是使问题复杂化。以下也不起作用:

Simple overloading does explain this error. In fact, std::cout just complicates the issue. The following also doesn’t work:

int main(){
  my_ostream s;
  s << 1;
}


$ b

The issue is that your operator << overload in effect hides all the overloads that are defined for the base class.

大致来说,C ++超载了分辨率。因此,C ++首先检查是否在类的范围中定义了运算符<< 。有!所以它停止搜索更一般的函数,只考虑已经发现的重载分辨率的函数。唉,只有一个重载, std :: string 所以调用失败。

Roughly speaking, C++ does overload resolution after scope resolution. So C++ first checks if there’s an operator << defined in the scope of your class. There is! So it stops searching for more general functions right there and only considers the functions already found for overload resolution. Alas, there’s only a single overload, for std::string so the call fails.

简单地定义运算符<< 不是成员函数,而是一个***函数:

This can be fixed simply by defining operator << not as a member function but a free function:

my_ostream& operator<<(my_ostream& out, const std::string &s) {
    std::cout << out.prefix << s;
    return out;
}

...但是这只修复了一些问题,只是语义错误;你不能这样子类化IO流。这里我的知识失败,但我想为了做你想要你应该重写流缓冲区的 uflow 函数。

… but of course this only fixes some of your problems because your class definition is simply semantically wrong; you cannot subclass the IO streams like this. Here my knowledge fails but I think in order to do what you want you should override the stream buffer’s uflow function.