[英]cout newly created object throws runtime error
I'm currently learning c++ and i'm struggling with an example that our tutor provided.我目前正在学习 C++,我正在为我们的导师提供的一个例子而苦苦挣扎。 He's creating a new Object ("Strudel") and immediately outputs it.
他正在创建一个新对象(“Strudel”)并立即输出它。
cout<<Strudel{"Nuss"};
this creates a runtime error.这会产生运行时错误。
operator<<(basic_ostream<_CharT, _Traits>& __os,
^
/usr/...../include/c++/9/ostream:548:5: note: candidate template ignored: could not match 'const _CharT *' against 'Strudel'
operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s)
I'm also not sure if this even works.我也不确定这是否有效。 I haven't found a single tutorial that does it like that beside what we saw in class.
除了我们在课堂上看到的内容之外,我还没有找到一个单独的教程可以做到这一点。
#include<iostream>
using namespace std;
class Strudel{
public:
string Inhalt;
Strudel(string x):Inhalt{x}{
if(Inhalt.size()==0){
throw runtime_error("kein Name!");
}
}
ostream& print(ostream & os){
return os<<this->Inhalt<<"-Strudel";
}
};
ostream & operator<<(ostream &os, Strudel &s){
return s.print(os);
}
int main(){
Strudel x{"Mohn"};
cout<<x<<endl;
cout<<Strudel{"Nuss"};
return 0;
}
Strudel{"Nuss"}
is a temporary value, these can't bind to non-const references (although visual studio erroneously allows you to). Strudel{"Nuss"}
是一个临时值,它们不能绑定到非常量引用(尽管 visual studio 错误地允许您这样做)。
You need to correct the signature of your operator to take a const reference:您需要更正操作员的签名以获取 const 引用:
ostream & operator<<(ostream &os, const Strudel &s){
You will then also need to mark print
as const
so that it can be called from a const
reference:然后,您还需要将
print
标记为const
,以便可以从const
引用中调用它:
ostream& print(ostream & os) const{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.