2012-02-24 12 views
16
class base{ 
    ..... 
    virtual void function1(); 
    virtual void function2(); 
}; 

class derived::public base{ 
    int function1(); 
    int function2(); 
}; 

int main() 
{ 
    derived d; 
    base *b = &d; 
    int k = b->function1() // Why use this instead of the following line? 
    int k = d.function1(); // With this, the need for virtual functions is gone, right? 

} 

Non sono un tecnico CompSci e mi piacerebbe saperlo. Perché utilizzare le funzioni virtuali se siamo in grado di evitare i puntatori della classe base?Perché utilizzare i puntatori di classe base per le classi derivate

risposta

47

Il potere del polimorfismo non è davvero appa affitto nel tuo semplice esempio, ma se lo estendi un po 'potrebbe diventare più chiaro.

class vehicle{ 
     ..... 
     virtual int getEmission(); 
} 

class car : public vehicle{ 
     int getEmission(); 
} 

class bus : public vehicle{ 
     int getEmission(); 
} 

int main() 
{ 
     car a; 
     car b; 
     car c; 
     bus d; 
     bus e; 

     vehicle *traffic[]={&a,&b,&c,&d,&e}; 

     int totalEmission=0; 

     for(int i=0;i<5;i++) 
     { 
      totalEmission+=traffic[i]->getEmission(); 
     } 

} 

In questo modo è possibile scorrere un elenco di puntatori e richiamare metodi diversi a seconda del tipo sottostante. Fondamentalmente consente di scrivere codice in cui non è necessario sapere quale sia il tipo di bambino in fase di compilazione, ma il codice eseguirà comunque la funzione corretta.

+6

Questo è probabilmente uno dei migliori esempi per l'uso di funzioni virtuali. Grazie! – Garfield

+0

Risposta brillante, ma quando so già che devo aggiungere le Emissioni per tutti questi oggetti di classe, perché non posso semplicemente creare manualmente gli oggetti per "auto" e "bus" e aggiungerli normalmente? Perché ho bisogno del puntatore del tipo di classe base. – Yankee

+0

Supponiamo che se non si utilizza la funzione virtuale, qual è il vantaggio dell'utilizzo di puntatori di classe base per la classe derivata? – Rajesh

4

Si è corretto, se si dispone di un oggetto non è necessario fare riferimento ad esso tramite un puntatore. Inoltre non è necessario un distruttore virtuale quando l'oggetto verrà distrutto come il tipo è stato creato.

L'utilità viene quando si ottiene un puntatore a un oggetto da un altro pezzo di codice e non si sa veramente quale sia il tipo più derivato. Puoi avere due o più tipi derivati ​​costruiti sulla stessa base e avere una funzione che restituisca un puntatore al tipo base. Le funzioni virtuali ti permetteranno di usare il puntatore senza preoccuparti di quale tipo derivato stai usando, finché non è il momento di distruggere l'oggetto. Il distruttore virtuale distruggerà l'oggetto senza che tu sappia a quale classe derivata corrisponde.

Ecco l'esempio più semplice di utilizzo di funzioni virtuali:

base *b = new derived; 
b->function1(); 
delete b; 
+1

Credo che la sua domanda era per questo uso puntatori di classe di base e non perché distruttori virtuale –

1

sua per implementare il polimorfismo. A meno che tu non abbia il puntatore della classe base che punta all'oggetto derivato non puoi avere il polimorfismo qui.

One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature, that brings Object Oriented Methodologies to its full potential.

In C++, a special type/subtype relationship exists in which a base class pointer or a reference can address any of its derived class subtypes without programmer intervention. This ability to manipulate more than one type with a pointer or a reference to a base class is spoken of as polymorphism.

Subtype polymorphism allows us to write the kernel of our application independent of the individual types we wish to manipulate. Rather, we program the public interface of the base class of our abstraction through base class pointers and references. At run-time, the actual type being referenced is resolved and the appropriate instance of the public interface is invoked. The run-time resolution of the appropriate function to invoke is termed dynamic binding (by default, functions are resolved statically at compile-time). In C++, dynamic binding is supported through a mechanism referred to as class virtual functions. Subtype polymorphism through inheritance and dynamic binding provide the foundation for objectoriented programming

The primary benefit of an inheritance hierarchy is that we can program to the public interface of the abstract base class rather than to the individual types that form its inheritance hierarchy, in this way shielding our code from changes in that hierarchy. We define eval(), for example, as a public virtual function of the abstract Query base class. By writing code such as _rop->eval(); user code is shielded from the variety and volatility of our query language. This not only allows for the addition, revision, or removal of types without requiring changes to user programs, but frees the provider of a new query type from having to recode behavior or actions common to all types in the hierarchy itself. This is supported by two special characteristics of inheritance: polymorphism and dynamic binding. When we speak of polymorphism within C++, we primarily mean the ability of a pointer or a reference of a base class to address any of its derived classes. For example, if we define a nonmember function eval() as follows, // pquery can address any of the classes derived from Query void eval(const Query *pquery) { pquery->eval(); } we can invoke it legally, passing in the address of an object of any of the four query types:

int main() 
{ 
AndQuery aq; 
NotQuery notq; 
OrQuery *oq = new OrQuery; 
NameQuery nq("Botticelli"); // ok: each is derived from Query 
// compiler converts to base class automatically 
eval(&aq); 
eval(&notq); 
eval(oq); 
eval(&nq); 
} 

che un tentativo di richiamare eval() con l'indirizzo di un oggetto non derivato da Query risultati in un errore di compilazione:

int main() 
{ string name("Scooby-Doo"); // error: string is not derived from Query 
eval(&name); 
} 

Within eval(), the execution of pquery->eval(); must invoke the appropriate eval() virtual member function based on the actual class object pquery addresses. In the previous example, pquery in turn addresses an AndQuery object, a NotQuery object, an OrQuery object, and a NameQuery object. At each invocation point during the execution of our program, the actual class type addressed by pquery is determined, and the appropriate eval() instance is called. Dynamic binding is the mechanism through which this is accomplished. In the object-oriented paradigm, the programmer manipulates an unknown instance of a bound but infinite set of types. (The set of types is bound by its inheritance hierarchy. In theory, however, there is no limit to the depth and breadth of that hierarchy.) In C++ this is achieved through the manipulation of objects through base class pointers and references only. In the object-based paradigm, the programmer manipulates an instance of a fixed, singular type that is completely defined at the point of compilation. Although the polymorphic manipulation of an object requires that the object be accessed either through a pointer or a reference, the manipulation of a pointer or a reference in C++ does not in itself necessarily result in polymorphism. For example, consider

// no polymorphism 
    int *pi; 
// no language-supported polymorphism 
    void *pvi; 
// ok: pquery may address any Query derivation 
    Query *pquery; 

In C++, polymorphism exists only within individual class hierarchies. Pointers of type void* can be described as polymorphic, but they are without explicit language support — that is, they must be managed by the programmer through explicit casts and some form of discriminant that keeps track of the actual type being addressed.

+0

l'ultima parte sono da C++ Primer! prendi quel libro e leggi Polymorphism –

0

ti sembra di avere chiesto a due domande (nel titolo e alla fine):

  1. Perché puntatori di classe l'uso di base per le classi derivate? Questo è l'uso del polimorfismo. Ti consente di trattare gli oggetti in modo uniforme mentre ti consente di avere un'implementazione specifica. Se questo ti infastidisce, allora presumo che dovresti chiedere: perché il polimorfismo?

  2. Perché utilizzare i distruttori virtuali se è possibile evitare i puntatori della classe base? Il problema qui è non è sempre possibile evitare i puntatori di classe di base per sfruttare la forza del polimorfismo.

Problemi correlati