The*_*ter 8 c++ friend-function
我创建了一个类,我想强制任何试图构建对象的人使用unique_ptr.为此,我想到声明构造函数protected并使用friend返回a 的函数unique_ptr.所以这是我想要做的一个例子:
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);
}
Run Code Online (Sandbox Code Playgroud)
我做了一些有关朋友函数的阅读,我理解朋友函数可以访问类对象的私有/受保护成员.
无论如何我可以让我的榜样有效吗?
即使没有朋友功能,我的目标也是让某人创建对象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;
}
Run Code Online (Sandbox Code Playgroud)
输出 :-
5
Run Code Online (Sandbox Code Playgroud)
如果您不想使用friend函数,您可以创建该函数static并像这样调用它:-
unique_ptr<A> u = A::CreateA(x);
Run Code Online (Sandbox Code Playgroud)
编辑 :-
为了回复您的编辑,我重写了程序,如下所示:-
#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;
}
Run Code Online (Sandbox Code Playgroud)
简单又容易!但请记住,您无法实例化object of A. 祝你好运 !!!