0

I'm currently learning c++ and i'm struggling with an example that our tutor provided. He's creating a new Object ("Strudel") and immediately outputs it.

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;
}
Gika
  • 143
  • 3
  • 2
    That's not a run-time error. That's a compile-time error. – Jesper Juhl Jan 23 '20 at 17:23
  • 3
    `#include ` ([and stop `using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). it's a terrible habit). – WhozCraig Jan 23 '20 at 17:24

1 Answers1

3

Strudel{"Nuss"} is a temporary value, these can't bind to non-const references (although visual studio erroneously allows you to).

You need to correct the signature of your operator to take a const reference:

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:

ostream& print(ostream & os) const{
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60