使用运算符重载时难以分离命名空间内类的标头/源代码

问题描述 投票:0回答:1

我在标头/源之间分离类似乎有效,直到我尝试在命名空间中使用类的声明。我相信这与指定命名空间内运算符的范围有关,但我不知道以这种方式正确重载运算符的语法。

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;
}

我知道它在标题中是这样解决的...

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

...我认为这与范围解析有关,但我不知道这是否是我实现命名空间、运算符或类本身的方式的问题。至少我确实知道,当我从命名空间中删除类声明时,它可以正常工作。它与 .cpp 内的范围解析有关吗?我该如何实现呢?

提前致谢。

编辑: test.number 在运算符重载的定义中无法访问......

c++ class scope header namespaces
1个回答
0
投票

当您在源文件中输入

using namespace testspace;
时,只会从命名空间导入名称以进行名称查找。如果你想向命名空间添加东西,比如你的
operator<<
,那么你需要使用

打开命名空间
namespace testspace {

然后添加操作符的实现,然后再次关闭命名空间

}

您可以根据需要多次打开命名空间以进行添加,跨多个文件或在同一文件内。都是加成的。

© www.soinside.com 2019 - 2024. All rights reserved.