gpt4 book ai didi

c++ - 全局命名空间好友类无法访问命名命名空间类的私有(private)成员

转载 作者:行者123 更新时间:2023-12-04 17:01:16 25 4
gpt4 key购买 nike

在命名命名空间类中,我将一个类(位于全局命名空间中)声明为友元。
但是,后一个类不能访问前一个类的私有(private)成员。为什么是这样?有什么办法可以解决吗?
Bob.h

namespace ABC {
class Bob {
friend class Joe;
public:
Bob ();
int pub_number;
private:
int priv_number;
};
}
Bob.cc
#include "Bob.h"

ABC::Bob::Bob () {
pub_number=10;
priv_number=6;
}
乔.h
class Joe {
Joe ( );
};
乔.cc
#include "Joe.h"
#include <iostream>
#include "Bob.h"

Joe::Joe ( ) {
ABC::Bob b;
std::cout << b.pub_number << std::endl;
std::cout << b.priv_number << std::endl;
}
上述代码在编译时产生以下错误:
Joe.cc:8:16: error: ‘int ABC::Bob::priv_number’ is private within this context
INFO: 1> 8 | std::cout << b.priv_number << std::endl;
如果我执行与上述相同的代码,但没有“Bob”类的任何命名空间,则代码将编译。
我试图在 Bob.h 中转发声明 Joe 类,如下所示:
class Joe; // This does nothing to help

class ::Joe // This produces compiler message "error: ‘Joe’ in namespace ‘::’ does not name a type"

最佳答案

您需要在全局命名空间中添加无作用域的前向声明,并在声明友元时使用作用域运算符:

class Joe;  // Forward declaration

namespace ABC {
class Bob {
friend class ::Joe; // Use the Joe class from the global scope
public:
Bob ();
int pub_number;
private:
int priv_number;
};
}

关于c++ - 全局命名空间好友类无法访问命名命名空间类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63900539/

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