C++如何编写一个位于单独编译单元中的命名空间中的友元函数二进制运算符



我似乎不知道如何编译以下内容。

我正在尝试写一个二进制运算符,它:

  • 在单独的编译单元(文件(中定义
  • 生活在嵌套的命名空间中

这里有一些代码:

// header.h
namespace ns1
{
namespace ns2
{
class myClass
{
friend bool operator==(const myClass& l, const myClass& r);
protected:
int a;
};
}
}
// header.cpp
#include "header.h"
using namespace ns1;
using namespace ns1::ns2;
bool operator==(const myClass& l, const myClass& r)
{
if(l.a != r.a) return false;
return true;
}
// main.cpp
#include "header.h"
using namespace ns1::ns2;
using namespace std;
int main()
{
myClass class1;
myClass class2;
if(class1 == class2)
{
cout << "hello world" << endl;
}
return 0;
}

这是编译器的输出:

In function ‘bool operator==(const ns1::ns2::myClass&, const ns1::ns2::myClass&)’:
error: ‘int ns1::ns2::myClass::a’ is protected within this context

我怀疑这与编译器不理解operator==应该在哪个命名空间中有关。我曾尝试过显式声明这一点,但这也没有帮助。

问题是这里发生了什么?编译器在想什么?

编辑

注意:我发布此编辑是为了回应一个答案,该答案随后被删除。建议将运算符放在ns1::ns2中,但这并不奏效。请参阅以下输出。

新的编译器输出:

error: ‘bool ns1::ns2::operator==(const ns1::ns2::myClass&, const ns1::ns2::myClass&)’ has not been declared within ‘ns1::ns2’ [-Werror]
bool ns1::ns2::operator==(const myClass& l, const myClass& r)
note: only here as a ‘friend’
friend bool operator==(const myClass& l, const myClass& r);

这里的问题是,当你在类中声明一个友元函数时,这个函数属于最内部的封闭命名空间,你必须定义

bool ns1::ns2::operator==(const myClass& l, const myClass& r)

它应该在命名空间ns1::ns2中定义,而不仅仅是用using指令、引入它

// header.cpp
#include "header.h"
namespace ns1 {
namespace ns2 {
bool operator==(const myClass& l, const myClass& r)
{
if(l.a != r.a) return false;
return true;
}
}
}

演示

// header.h
namespace ns1
{
namespace ns2
{
class myClass
{
...
};
bool operator==(const myClass& l, const myClass& r);
}
}

// header.cpp
bool ns1::ns2::operator==(const myClass& l, const myClass& r)

演示


另一种方法是将您的友元函数声明为全局函数

// header.h
#pragma once
namespace ns1
{
namespace ns2
{
class myClass;
}
}
bool operator==(const ns1::ns2::myClass& l, const ns1::ns2::myClass& r);
namespace ns1
{
namespace ns2
{
class myClass
{
friend bool ::operator==(const myClass& l, const myClass& r);
protected:
int a;
};
}
}
// header.cpp
#include "header.h"
using namespace ns1::ns2;
bool operator==(const myClass& l, const myClass& r)
{
if(l.a != r.a) return false;
return true;
}

演示

最新更新