[C++] In care cazuri nu se pot supraincarca functiile?

Despre limbajul de programare C++ si biblioteca standard STL (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[C++] In care cazuri nu se pot supraincarca functiile?

Post by Ovidiu Cucu » 23 May 2011, 13:28

Intrebare
In care cazuri nu se pot supraincarca functiile?

Raspuns
Functiile nu pot fi supraincarcate in urmatoarle cazuri:
  1. Difera numai tipul de return.

    Code: Select all

    void f(int);
    int f(int); // Error: overloaded function differs only by return type
  2. Functii membru care au parametri de acelasi tip, daca una dintre ele e declarata 'static'.

    Code: Select all

    class CFoo
    {
       static int f(int); 
       int f(int);         // Error
       int f(int) const;   // Error
       // cannot overload static and non-static member functions with the same parameter types
    };
  3. Tipul parametrilor sunt tipuri echivalente declarate cu 'typedef'.

    Code: Select all

    typedef int Int;
    
    void f(int);
    void f(Int); // OK: redeclaration of f(int)
    
    void f(int i) {/*...*/}
    void f(Int i) {/*...*/} // Error: redefinition of f(int)
  4. Tipul parametrilor difera doar prin pointer * versus array [].

    Code: Select all

    void f(int*);
    void f(int [5]); // OK: redeclaration of 'void f(int*)'
    
    void f(int* p) {/*...*/}
    void f(int a[5]) {/*...*/} // Error: redefinition of 'void f(int*)'
  5. Parametrii difera doar prin prezenta lui 'const' sau 'volatile'.

    Code: Select all

    void f(int);
    void f(const int); // OK: redeclaration of 'void f(int)'
    
    void f(int i) {/*...*/}
    void f(const int i) {/*...*/} // Error: redefinition of 'void f(int)';
    '
  6. Parametrii difera doar ca fiind de tip functie sau pointer la functie.

    Code: Select all

    void g(int());
    void g(int(*)); // OK: redefinition of 'void g(int())'
    
    void g(int f()) {/*...*/}
    void g(int (*pf)()) {/*...*/} // Error: redefinition of 'void g(int())'
  7. Rezulta ambiguitate datorita parametrilor impliciti.

    Code: Select all

    void f (int i = 1);
    void f (); // OK: overloaded declaration of f
    
    void f(int i /*=1*/) {/*...*/}
    void f () {/*...*/} // OK: overloaded definition of f
    
    void foo()
    {
       f(1); // OK: call f(int)
       f();  // Error: ambiguous call to overloaded function (f(int) or f()?)
    }
Resurse
  • ISO/IEC 14882:2003 Programming languages — C++



Post Reply