C++ 友元跨命名空间使用
以+
运算符重载为例:
#include <iostream>
#include <string>
// 前置声明是必须的
namespace mydog
{
class Dog;
}
namespace myadd
{
mydog::Dog operator+(const mydog::Dog dog1, const mydog::Dog dog2);
}
namespace mydog
{
class Dog
{
friend Dog myadd::operator+(const Dog dog1, const Dog dog2);
private:
std::string name{ "小黑" };
int age{ 2 };
public:
void show()
{
std::cout << "名字:" << name << " " << "年龄:" << age << '\n';
}
Dog() = default;
Dog(const std::string &n, int a):name{n}, age{a}{}
};
}
mydog::Dog myadd::operator+(const mydog::Dog dog1, const mydog::Dog dog2)
{
mydog::Dog my_dog_add;
my_dog_add.age = dog1.age + dog2.age;
my_dog_add.name = dog1.name + "+" + dog2.name;
return my_dog_add;
}
int main()
{
using mydog::Dog;
Dog dog1("小花", 3);
Dog dog2;
using myadd::operator+; // 必须不然找不到函数,或者直接 using namespace myadd;加入命名空间
Dog addDog = dog1 + dog2;
addDog.show();
system("pause");
return 0;
}
输出:
名字:小花+小黑 年龄:5
类型的前置声明貌似是必须的,不然编译器好像连接不到。
另外,友元关系不继承,且与放到private或public无关。