C++私有构造函数(带参数)不允许实例化
C++ private constructor (with argument) does not allow instantiation
我的私有构造函数有一个问题,如下所示:
Lane.hpp:
namespace sim_mob
{
class B
{
friend class A;
private:
B(int){}
};
}
xmll.hpp:
#include"Lane.hpp"
namespace geo
{
class A
{
public:
A()
{
sim_mob::B b(2);
}
};
}
main.cpp:
#include"xmll.hpp"
int main()
{
geo::A a;
return 0;
}
命令:$g++main.cpp
In file included from main.cpp:2:0:
Lane.hpp: In constructor ‘geo::A::A()’:
Lane.hpp:10:5: error: ‘sim_mob::B::B(int)’ is private
xmll.hpp:9:23: error: within this context
关键是,如果我在构造函数中没有任何参数,我就不会收到这个错误。我可以知道我为什么会得到这个以及如何解决它吗?非常感谢
在类sim_mob::B
中,你与类sim_mob:A
交上了朋友,但你希望这种友谊能延伸到geo::A
,但显然没有。为了解决这个问题,在将其作为朋友之前,您需要声明geo::A
:
namespace geo { class A; }
namespace sim_mob
{
class B
{
friend class geo::A;
private:
B(int){}
};
}
它与默认构造函数"一起工作"的事实是,我想,你宁愿声明一个函数,也不愿实例化一个对象:
sim_mob::B b();
是一个函数声明。如果你去掉括号,你应该得到一个关于默认构造函数不存在的错误,或者,如果你真的声明了它,它是不可访问的。
正向声明:
namespace geo{
class A;
}
B类:
friend class geo::A;
friend class A;
朋友类A
在当前命名空间中,即sim_mob::A
,而不是geo::A
。您需要声明类,然后使用完全限定名称:
namespace bar { struct bar; }
namespace foo {
struct foo {
private:
friend struct bar::bar;
explicit foo(int) {}
};
}
namespace bar {
struct bar {
bar() { foo::foo x(42); }
};
}
相关文章:
- 不允许运算符 const 参数调用 const 成员函数
- 为什么C++不允许两个同名的函数/类模板,区别仅在于非类型模板参数(整型)的类型?
- antlr cpp target 的标头部分不允许使用具有默认参数的外部函数
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么不允许自动作为函数参数?
- 为什么函数返回类型中不允许参数推导?
- 网站组装 |错误:'C/ObjC'不允许使用无效'-std=c++11'参数
- 如何编写模板重载函数,并在模板参数不允许实例化某个类时触发回退
- C++ 不允许将'this'用作非类型模板参数
- 是否不允许编译器假设 const-ref 参数将保持 const?
- 为什么在lambda参数中不允许自动
- 为什么C++不允许参数成为默认参数
- 在 QGraphicsScene 中拖动 QPixmap:如何避免 lambda 参数中不允许'auto'
- 传递动态大小的数组(不允许使用参数)
- 不允许非类型参数的部分模板专用化
- 为什么C 不允许在非模板函数中进行变异参数
- 为什么不允许我提供函数参数
- 整型常量表达式中不允许使用模板参数
- 为什么模板模板参数不允许在参数列表后使用"typename"
- 为什么默认参数不允许出现在非默认参数之前