More Effective C ++ 25

xiaoxiao2021-04-01  230

Terms 25: Sending Constructor and Non-Member Functions

Virtual constructor: This noun is a little horrible. The C constructor does not allow virtual, then what kind of meaning is this virtual constructor?

Consider the following code:

Class base // base class

{

}

Class Derivea: Public Base

{

}

Class Deriveb: Public Base

{

}

Class Classset

{

PUBLIC:

Classset (ISTREAM & STR)

{

While (STR)

Components.push_back (getObject (STR))

}

Static Base * GetObject (istream & Str);

Private:

Vector company;

}

The so-called virtual constructor is the constructor of class Classset, which enables Components to be initialized to various types of inheritance class. This is the so-called virtual constructor, I look very similar to the object factory. In the past program design, this is what we often use.

Consider the following code:

Class base // base class

{

Virtual base * clone () const = 0;

}

Class Derivea: PUBLIC BASE

{

Virtual Derivea * Clone () Const

{Return New Derivea (* this);

}

Class Deriveb: Public Base

{

Virtual Deriveb * Clone () Const

{RETURN New Deriveb (* this);

}

Class Classset

{

PUBLIC:

Classset (Const Classset & RHS)

{

/ / There is a bug here, rhs.components.begin () is illegal

For (Vector :: item = rhs.components.begin (): iter! = rhs.end (); iter )

Components.push_back ((* iter) -> clone);

}

Static Base * GetObject (istream & Str);

Private:

Vector company;

}

Is this called a virtual copy constructor? I have no problem in this code now, I need to pay attention to deepening the STL.

The virtualization of non-member functions is very simple, just writes a virtual function to do actual work, then write a non-member function, it is only responsible for calling the virtual function. In order to reduce costs, non-member functions can be inline.

Consider the following code

Class base // base class

{

Virtual Ostream * Print (Ostream & S) Const = 0;

}

Class Derivea: Public Base

{

Virtual Ostream * Print (Ostream & S) Const

{Return New Derivea (* this);

}

Class Deriveb: Public Base

{

Virtual Ostream * Print (Ostream & S) Const}

}

Inline Operator << (Ostream & S, Const Base & C)

{

Return C.Print (s);

}

转载请注明原文地址:https://www.9cbs.com/read-131187.html

New Post(0)