【发布时间】:2021-01-02 03:12:37
【问题描述】:
在命名空间类中,我将一个类(在全局命名空间中)声明为友元。 但是,后一个类不能访问前一个类的私有成员。为什么是这样?有什么办法吗?
鲍勃.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;
}
Joe.h
class Joe {
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"
【问题讨论】:
-
你把
Joe的前向声明放在Bob.h的什么地方?如果它在namespace ABC内部,它不会声明与全局命名空间中相同的类。 -
我试着把它放在不同的地方。我在命名空间外、命名空间内和类内尝试过。都给出了相同的结果。
标签: c++ class namespaces friend name-lookup