Chinaunix首页 | 论坛 | 博客
  • 博客访问: 772696
  • 博文数量: 217
  • 博客积分: 2401
  • 博客等级: 大尉
  • 技术积分: 2030
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-16 06:58
个人简介

怎么介绍?

文章分类

全部博文(217)

文章存档

2023年(2)

2022年(3)

2021年(29)

2020年(12)

2019年(5)

2018年(5)

2017年(5)

2016年(3)

2015年(6)

2014年(12)

2013年(16)

2012年(9)

2011年(6)

2010年(15)

2009年(30)

2008年(59)

我的朋友

分类:

2009-02-20 15:55:08

Realize virtual constructor through clone() function.

Textblock *a=previousObject.clone();

class NLComponent { public: 
  // declaration of virtual copy constructor 
  virtual NLComponent * clone() const = 0; 
  ... 

}; 

class TextBlock: public NLComponent { 
public: 
  virtual TextBlock * clone() const // virtual copy 
  { return new TextBlock(*this); } // constructor 

  ... 

}; 

class Graphic: public NLComponent { 
public: 
  virtual Graphic * clone() const // virtual copy 
  { return new Graphic(*this); } // constructor 

  ... 

}; 

Notice that the above implementation takes advantage of a relaxation in the rules for virtual function return types that was adopted relatively recently. No longer must a derived class's redefinition of a base class's virtual function declare the same return type. Instead, if the function's return type is a pointer (or a reference) to a base class, the derived class's function may return a pointer (or reference) to a class derived from that base class. This opens no holes in C++'s type system, and it makes it possible to accurately declare functions such as virtual copy constructors. That's why TextBlock's clone can return a TextBlock* and Graphic's clone can return a Graphic*, even though the return type of NLComponent's clone is NLComponent*. 

阅读(792) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~