我正在尝试与一个类成为朋友,以便它能够到达它的私有构造函数.
在some_file.h中
class B;
namespace some_name {
class A {
public:
A() {}
private:
A (int x) {}
friend class ::B;
};
}
Run Code Online (Sandbox Code Playgroud)
在other_file.h中
#include "some_file"
namespace {
class B {
protected:
A* get_a(int x) { return new A(x); }
};
}
Run Code Online (Sandbox Code Playgroud)
编译此代码时,我得到 - 错误:'some_name :: A :: A(int)'是私有的.
我现在,这是私人的,这就是我成为朋友的原因B.我在这里做错了什么?你不能和你的构造者成为朋友吗?是否有命名空间问题?
谢谢
这样做:
namespace {
class B {
protected:
A* get_a(int x) { return new A(x) };
}
}
Run Code Online (Sandbox Code Playgroud)
你没有放入Broot(全局)命名空间,而是放在匿名命名空间中.
所以B无法达成::B.
如果您想要B位于根(全局)命名空间中,则根本不要将其括起来namespace.这应该可以解决问题.
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |