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?
You want to make the name()
method const
:
class ElementCopy
{
public:
std::string name() const;
};
This way, you will be allowed to call it on the const
reference in your operator<<
Your argument arg
is a const
reference, but the ElementCopy::name
method is non-const. Just add a const
:
std::string name() const;
您的name()
方法不是const,您可能希望在声明之后添加const
。
The operator needs to be a free function, since the left argument is the stream, not your object. You typically achieve this by making it a friend inside your class:
friend std::ostream& operator<< (std::ostream& stream, const ElementCopy& arg)
{
return stream << arg.name();
}
Since name()
is a public member function, you can also declare this entire thing outside the class definition. The friend
relationship is typically used to access private members conveniently without requiring getters just for the sake of the stream operator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.