c++ - c++ exception to return type match and virtually virtual new operator

本文探讨了通过指针或引用复制对象的方法,并提出了一种使用克隆接口来实现对象复制的设计模式。文中还详细解释了如何在派生类中正确实现此模式,确保能够创建与原始对象类型相匹配的新实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How do we duplicate a object through its pointer or reference? suppose 

 

NotQuery *pnq;

NotQuery *pnq2 = new NotQuery(*pnq);

 

 

however, what if we have this ?

 

 

const Query *pq = pnq->op();

// ???

 

 

we cannot dclare a virutal new instance of operator new, the new operator is a static member, and it applies before the constructor. 

 

THINK:??? you can overload new operator inside the class, , however, we cannot make it virtual still it does not answer the time/order problem.

 

the solution is a surrogate, somehting like this:

 

 

public Query {
public:
   virtual Query * clone() = 0;
};
 

 

however, if we cannot change the return type in the derived class, then we might see this

 

 

NameQuery *png = new NameQuery("Rike");
NameQuery *pnq2 = static_cast<NameQuery*> (pnq->clone());

 

BUT!!!,there is an exception to that "requirement that return type of the derived class must match exactly that of the base class".

 

 

so, in the derived class, you can write 

 

public NameQuery : public Query 
{
public:
  virtual NameQuery* clone() { return new NameQuery(*this); }
};

 

 

Below shows the whole code ::

 

class Base 
{
public :
	Base() { }
	Base(Base &base) {}
	virtual Base *clone();
protected:
	Base *print();
private:

};

class Derived : public Base {
public:
	Derived() {}
	Derived (Derived &derived) : Base(derived) {} 
	virtual Derived *clone();
protected:
	Base *print();

};

Base* Base::clone(){ 
	return new Base(*this);
}

Derived* Derived::clone() {
	return new Derived(*this);
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值