I'm doing a refresher for C++ and have gotten to operator overloading. I'm trying to perform an operator overload with the insertion (<<) operator, but I have encountered a problem.
If the operator function is a friend of the 'Shinigami' class, why doesn't it recognize any of it's private members? I need it to be in this file because I'm doing a bit of association with the 'Quincy' class.
I thought it was the namespace, but I included that.
namespace K{ class Shinigami; }
std::ostream& operator<<(std::ostream&, const K::Shinigami&);
on top of your header (This is forward declaration) and change declaration inside class to: friend std::ostream& (::operator<<)(std::ostream&, const Shinigami&);
That didn't work, it's private members are still inaccessible.
Btw, I don't have to use a forward declaration since I'm including the class with the header 'Shinigami.h'.
Did you read the article I provided? Did you tried what I proposed exactly? If so, show, how your header looks after that.
Because it works with changes I propose for me.
Btw, I don't have to use a forward declaration since I'm including the class with the header 'Shinigami.h'.
Uh, no, you do need to use forward declaration as @NiiNiPaa said. The forward declaration has to be within the header file, forward declaring something fully declared later in the same file.
You need to
- forward delcare K::Shinigami
- then foward declare operator<<(std::ostream&, const K::Shinigami&)
- then declare K::Shinigami, with it's friend, which was just forward declared.
Thanks MiiNiPaa; i was wrong, the code compiled and worked as expected. But, would you mind explaining how this works? Like why do do I have to make a forward declaration for the namespace and (prototype?) for the operator overload. Also, what's the deal with this (::operator<<) ?
:: is a scope resolution operator. ::operator<< tells, that operator<< is in global namespace. For some reason compiler doesn't accept this as declaration and gives an error operator<< isn't declared. So we need forward declaration of operator in global namespace. If we do so, compiler will tell, that class K::Shinigami wasn't declared, so we need to forward declare class Shinigami inside K namespace.
cire's method will work too. I had doubts if operator will work without usingnamespace K; or K:: specification for operator, but other sources told me that everything will be fine.