Search code examples
c++classscopeheadernamespaces

Difficulty separating header/source of a class within a namespace while using operator overload


My separation of a class between a header/source seems to work until I try to work with the declaration of the class within a namespace. I believe it has to do with the scope of the operator within the specified namespace, but I don't know the syntax to correctly overload the operator in this way.

NameTest.h

#pragma once

#include <iostream>

namespace testspace
{
    class Test
    {
    private:
        int number{};
    
    public:
        friend std::ostream& operator<< (std::ostream& out, const Test& test);
    };
}

NameTest.cpp

#include "NameTest.h"

using namespace testspace;

std::ostream& operator<< (std::ostream& out, const Test& test)
{
    out << test.number;
    return out;
}

I know it is resolving like this in the header...

(std::ostream &testspace::operator<< (std::ostream &out, const testspace::Test& test);

...and I think it has something to do with scope resolution, but I don't know if it is a problem with the way I am implementing the namespace, the operator, or the class itself. I do know, at least, that when I remove the class declaration from the namespace it works fine. Does it have to do with scope resolution within the .cpp? And how would I implement that?

Thanks in advance.

EDIT: test.number is inaccessible within the definition of the operator overload as it stands...


Solution

  • When you say using namespace testspace; in the source file, that just imports names from the namespace for name lookup. If you want to add things to the namespace, like your operator<<, then you need to open up the namespace with

    namespace testspace {
    

    and then add the implementation of the operator and then close the namespace again

    }
    

    You can open up a namespace for additions as many times as you need/want, across multiple files or inside the same file. It's all additive.