【问题标题】:Can't access private constructor from a friend class [duplicate]无法从朋友类访问私有构造函数
【发布时间】:2022-07-22 21:53:46
【问题描述】:

在以下代码sn-p中,g++编译器输出如下错误:

错误:“B::B(const string&)”在此上下文中是私有的 857 |
{ return unique_ptr<_tp>(new _Tp(std::forward<_args>(__args)...)); }

注释掉使用智能指针的行似乎有效。但是,我不确定为什么它适用于其他情况,并且仍然不适用于智能指针情况。

#include <memory>
#include <iostream>
#include "string"

class A;

class B
{
  friend class A;
  B(const std::string& dummyString) {std::cout << dummyString << std::endl;}
};

class A
{
  public:
    A()
    {
        B b("dummy1");
        B* pB1 = new B("dummy2");
        std::unique_ptr<B> pB2 = std::make_unique<B>("dummy3");
    }
};

int main()
{
    A a;
}

【问题讨论】:

  • 因为std::make_unique不是A的成员,因此不是B的朋友

标签: c++ friend-class private-constructor


【解决方案1】:

问题在于应该构造B 实例的make_unique 不是B 的朋友。因此它确实 可以访问B 的私​​有构造函数。

您可以使用以下方法来实现类似的效果:

std::unique_ptr<B> pB2 = std::unique_ptr<B>(new B("dummy3"));

一般来说,建议您更喜欢make_unique 而不是自己打电话给new,我不鼓励这样做。
但是,如果您受制于这种特定的类层次结构,它将解决您的问题。

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2013-06-30
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多