I am trying to overload the <<
-operator for a class so that I can use std::cout
with it. I've copied some code I found online to do this, but I can't get it to work.
I get an error that says:
error C2662: 'nspace::ElementCopy::name' : cannot convert 'this' pointer
from 'const nspace::ElementCopy' to 'nspace::ElementCopy &'
The error is in the <<
-operator implementation: (see my code comment)
Here is my 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 at this line
return stream;
}
}
And here is my short code file, ElementCopy.cpp:
#include "ElementCopy.h"
namespace nspace
{
std::string ElementCopy::name()
{
return "string";
}
}
I can't figure out this error. Why am I getting it? That operator overload doesn't have a "this"
to speak of. How can I fix this?