Which situation will use clone in C++ and how to use it?

后端 未结 2 1423
粉色の甜心
粉色の甜心 2021-01-24 12:04

What is the difference between virtual clone and clone? I find the following example, it clone derived to base, what is it for?

class Base{
public:
    virtual B         


        
2条回答
  •  面向向阳花
    2021-01-24 12:20

    Consider this:

    Base * b = get_a_base_object_somehow();
    

    // now, b might be of type Base, or Derived, or something else derived from Base

    Base * c = b->clone();
    

    // Now, c will be of the same type as b was, and you were able to copy it without knowing its type. That's what clone methods are good for.

提交回复
热议问题