私有构造函数
我有一个具有私有构造函数的类对象:
class CL_GUIComponent
{
// ...
private:
CL_SharedPtr<CL_GUIComponent_Impl> impl;
CL_GUIComponent(CL_GUIComponent &other);
CL_GUIComponent &operator =(const CL_GUIComponent &other);
CL_GraphicContext dummy_gc;
};
我有一个类,它有一个指向我之前描述的类型的对象的指针。
class Some
{
private:
CL_GUIComponent *obj;
public:
CL_GUIComponent getComp() { return *obj; }
}
但是这段代码调用了错误:
In member function ‘CL_GUIComponent Some::getComp()’:
error: ‘CL_GUIComponent::CL_GUIComponent(CL_GUIComponent&)’ is private
error: within this context
我如何存储和获取该对象?
I have an object of class which has private constructor:
class CL_GUIComponent
{
// ...
private:
CL_SharedPtr<CL_GUIComponent_Impl> impl;
CL_GUIComponent(CL_GUIComponent &other);
CL_GUIComponent &operator =(const CL_GUIComponent &other);
CL_GraphicContext dummy_gc;
};
I have a class which has a pointer to the object of the type I described before.
class Some
{
private:
CL_GUIComponent *obj;
public:
CL_GUIComponent getComp() { return *obj; }
}
But this code calls the error:
In member function ‘CL_GUIComponent Some::getComp()’:
error: ‘CL_GUIComponent::CL_GUIComponent(CL_GUIComponent&)’ is private
error: within this context
How can I store and get that object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
返回一个引用:
和/或
您拥有的代码试图返回一个副本,但复制构造函数是私有的,因此它无法访问它(因此出现错误)。无论如何,对于重要的对象,返回 const& 几乎总是更好(一般情况下,并非总是如此)。
Return a reference instead:
and/or
The code you have their is trying to return a copy, but the copy constructor is private so it can't access it (hence the error). In any case, for non trivial objects, it's almost always better to return a
const&
instead (in general, not always).通过指针或引用。您无法构建新的副本,因此无法像您的 get 尝试那样返回副本。
By pointer or reference. You can't construct a new one and thus can't return copies, as your get attempts to do.
getComp 返回 CL_GUIComponent 的实例。这意味着 getComp 实际上会复制 obj 所指向的实例。如果您希望 getComp 返回 obj 所指向的实例,请返回对 CL_GUIComponent 的引用,如下所示:
getComp returns an instance of CL_GUIComponent. This means that getComp will actually make a copy of the instance pointed to by obj. If you want getComp to return the instance where obj is pointing to, return a reference to CL_GUIComponent, like this:
这是不可复制习语在行动中。通过指针或引用返回。
This is non-copyable idiom in action. Return by pointer or reference.
使用
getComp()
初始化引用。然后该语言不会尝试调用调用函数内的复制构造函数。 (不过,
getComp
仍然创建并返回一个副本。)Use
getComp()
to initialize a reference.Then the language doesn't try to invoke the copy constructor inside the calling function. (
getComp
does still create and return a copy, though.)由于构造函数被声明为私有,因此您必须使用公共成员函数来创建使用私有构造函数的类的对象。
Since the constructor is declared private, you have to use a public member function to create an object of class that uses the private constructor.