gpt4 book ai didi

c++ - 命名空间内类的友元函数的定义。

转载 作者:搜寻专家 更新时间:2023-10-31 00:45:25 25 4
gpt4 key购买 nike

我正在阅读 C++ Primer,作者说,

"If a class is defined inside a namespace, then an otherwise undeclared friend function is declared in the same namespace:

      namespace A {
class C {
public:
friend void f(const C&); // makes f a member of namespace A
};
}

这是否意味着我不必在命名空间内再次声明函数 f()?

当我简单地将命名空间外的函数 f() 定义为

void
A::f(const C& obj)
{
std::cout << "f(const C&) " << std::endl;
}

我从 g++ 4.5 中得到错误,

FriendDeclarations1.cpp:40:23: error: ‘void A::f(const A::C&)’ should have been declared inside ‘A’

谁能告诉我作者的意思是什么?

最佳答案

作者的意思是,如果未明确声明其命名空间,则友元函数在同一类命名空间内隐式声明。

所以 f 需要在命名空间 A 中定义

#include <iostream>

namespace A {
class C {
friend void f(const C&); // makes f a member of namespace A
int i;

public:
C() : i(42) {}
};

void f(const A::C& obj)
{
std::cout << "f(const A::C&) " << std::endl;
std::cout << "obj.i = " << obj.i << std::endl; // access private member
}
}

int main()
{
A::C ac;

f(ac);
return 0;
}

您可以通过显式声明 f 所属的命名空间来更改此行为

#include <iostream>

// forward declarations
namespace A { class C; }
namespace B { void f(const A::C&); }

namespace A {
class C {
friend void B::f(const C&);
int i;

public:
C() : i(42) {}
};
}

namespace B {
void f(const A::C& obj)
{
std::cout << "f(const A::C&) " << std::endl;
std::cout << "obj.i = " << obj.i << std::endl; // access private member
}
}

int main()
{
A::C ac;

B::f(ac);
return 0;
}

关于c++ - 命名空间内类的友元函数的定义。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6866226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com