gpt4 book ai didi

c++ - 将 friend 声明注入(inject)命名空间,Eckel,Vol1,pg :440?

转载 作者:太空狗 更新时间:2023-10-29 23:07:49 25 4
gpt4 key购买 nike

我试图理解将友元声明注入(inject)命名空间:

#include <iostream>
using namespace std;

namespace Z { //forward declaration
class X;
}

class Y {
public:
void func(Z::X*, int);
};

namespace Z {
class X {
int i;
public:
X() : i(999) {}
friend void Y::func(Z::X*, int);
void print(void) { cout << i << endl; }
};
}


void Y::func(Z::X* ptr, int i)
{
ptr->i = 40;
}

int main(void)
{
Z::X zx;
zx.print();

Y y;
y.func(&zx, 40);
zx.print();

using namespace Z;
// func(&zx, 30); DOES NOT WORK
}

friendInject.cc:39: error: 'func' was not declared in this scope The book says: "You can inject a friend declaration into a namespace by declaring it within an enclosed class". "Now the function you() is a member of the namespace Me."

这到底是什么意思??我试过 Y::func 但这可能只适用于静态成员函数??

最佳答案

你必须写

y.func(&zx, 30); // work well

与 y。因为基金 - 它是一个类实例方法

关于c++ - 将 friend 声明注入(inject)命名空间,Eckel,Vol1,pg :440?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505226/

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