gpt4 book ai didi

c++ - 如何从友元函数访问 protected 构造函数?

转载 作者:可可西里 更新时间:2023-11-01 17:50:19 26 4
gpt4 key购买 nike

我创建了一个类,我想强制任何试图构建对象的人使用 unique_ptr。为此,我考虑声明构造函数 protected 并使用返回 unique_ptrfriend 函数。所以这是我想做的一个例子:

template <typename T>
class A
{
public:
friend std::unique_ptr<A<T>> CreateA<T>(int myarg);

protected:
A(int myarg) {}
};

template <typename T>
std::unique_ptr<A<T>> CreateA(int myarg)
{
// Since I declared CreateA as a friend I thought I
// would be able to do that
return std::make_unique<A<T>>(myarg);
}

我阅读了友元函数,了解到友元函数提供对类对象的私有(private)/ protected 成员的访问。


无论如何我可以让我的例子工作吗?

即使没有友元函数,我的目标也是让 CreateA 成为某人创建对象的唯一方式。

编辑

我稍微更改了代码。我没有提到我的类采用一个模板参数。这显然使事情变得更加复杂。

最佳答案

你可以这样做:-

#include <iostream>
#include <memory>
using namespace std;
class A
{
int arg;
public:
friend unique_ptr<A> CreateA(int myarg);
void showarg() { cout<<arg; }

protected:
A(int myarg): arg(myarg) {}
};
unique_ptr<A> CreateA (int myarg)
{
return std::unique_ptr<A>(new A(myarg));
}
int main()
{
int x=5;
unique_ptr<A> u = CreateA(x);
u->showarg();
return 0;
}

输出:-

5

如果您不想使用friend 函数,您可以将函数设置为static 并像这样调用它:-

unique_ptr<A> u = A::CreateA(x);

编辑:-

为了回复您的修改,我重写了程序,它是这样的:-

#include <iostream>
#include <memory>
using namespace std;
template <typename T>
class A
{
T arg;
public:
static std::unique_ptr<A> CreateA(T myarg)
{
return std::unique_ptr<A>( new A(myarg) );
}
void showarg()
{
cout<<arg;
}
protected:
A(T myarg): arg(myarg) {}
};

int main()
{
int x=5;
auto u = A<int>::CreateA(x);
u->showarg();
return 0;
}

简单易行!!!但请记住,您无法实例化 A 的 对象。祝你好运!!!

关于c++ - 如何从友元函数访问 protected 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33902005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com