【问题标题】:C++ private constructor (with argument) does not allow instantiationC++ 私有构造函数(带参数)不允许实例化
【发布时间】:2012-03-18 14:00:11
【问题描述】:

我的私有构造函数有如下问题:

车道.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

关键是如果我在构造函数中没有任何参数,我就不会收到这个错误。我可以知道为什么我会得到这个以及如何解决它吗? 非常感谢

【问题讨论】:

    标签: c++ constructor private friend


    【解决方案1】:

    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();
    

    是一个函数声明。如果你去掉括号,你应该得到一个关于默认构造函数不存在的错误,或者,如果你真的声明了它,它是不可访问的。

    【讨论】:

      【解决方案2】:

      转发声明:

      namespace geo{
      class A;
      }
      

      B 类:

      friend class geo::A;
      

      【讨论】:

        【解决方案3】:

        friend class A;friends class 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); }
            };
        }
        

        【讨论】:

          猜你喜欢
          • 2011-09-12
          • 1970-01-01
          • 1970-01-01
          • 2020-01-06
          • 2018-03-11
          • 2014-02-03
          • 1970-01-01
          • 2021-08-17
          • 2012-08-26
          相关资源
          最近更新 更多