c++ - What is wrong with my operator<< overload code? -
i trying overload <<-operator class can use std::cout it. i've copied code found online this, can't work.
error says:
error c2662: 'nspace::elementcopy::name' : cannot convert 'this' pointer 'const nspace::elementcopy' 'nspace::elementcopy &' the error in <<-operator implementation: (see code comment)
here header file, elementcopy.h:
#pragma once #include <string> #include <iostream> namespace nspace { class elementcopy { public: std::string name(); }; std::ostream& operator<< (std::ostream& stream, const elementcopy& arg) { stream << arg.name(); //compiler error @ line return stream; } } and here short code file, elementcopy.cpp:
#include "elementcopy.h" namespace nspace { std::string elementcopy::name() { return "string"; } } i can't figure out error. why getting it? operator overload doesn't have "this" speak of. how can fix this?
you want make name() method const:
class elementcopy { public: std::string name() const; }; this way, allowed call on const reference in operator<<
Comments
Post a Comment