考虑以下示例。
class Parent
{
public:
Child createChild();
// some member data and functions can go here.
}
class Child: public Parent
{
// some member data and functions can go here.
}
我只想通过父类中提供的方法允许创建"孩子"类。那是我想拒绝用户实例化子类对象的选项。我也想避免儿童课的所有其他默认结构。怎么可能?
Parent p;
Child c = p.createChild(); // should be possible
Child d; //should not be allowed
Child e = c; // may be allowed
您可以制作Child
构造函数private
,并且使Parent::createChild
是Child
的friend
。
请注意讲故事的评论,因为您的副本构造人仍然需要公开。
您可以做这样的事情。
class Parent
{
public:
static Parent* InstantiateParent(); // for completeness' sake
static Child* InstantiateChild();
};
class Child : public Parent
{
Child();
Child(Child& other):
Child& operator = (Child& other);
friend class Parent;
public:
};
/* impl.cpp */
#include "header.hpp";
Child* Parent::InstantiateChild()
{
return new Child;
}
Parent* Parent::InstantiateParent()
{
return new Parent;
}
,尽管通过工厂模式的某种变化将创建与目标类别分开。
您可以让createChild((返回孩子以外的其他东西,这是对孩子公开构建的。您为这一举动付费,因为它没有复制,并且代码是多余的C 17。
您可以忍受临时延长其寿命的临时或正确的参考吗?我认为在任何情况下,它不会拥有与直接创建的不可复制对象相同的寿命。