2009-01-24 5 views
1
class test { 
public: 
    test &operator=(const test & other){} // 1 
    const test & operator+(const test& other) const {} // 2 
    const test & operator+(int m) {} //3 
private: 
    int n; 
}; 

int main() 
{ 
test t1 , t2, t3; 

// this works fine t1 = t2.operator+(t3) , calls 2 and 1 
t1 = t2 + t3; 

// this works fine t1 = t2.operator+ (100). calls 3 and 1 
t1 = t2 + 100; 

//this works fine t1 = (t2.operator+ (100)).operator+ (t3) 
t1 = t2 + 100 +t3; 

//why is the error in this one ???? 
// it should be t1 = (t2.operator+ (t3)).operator+ (100) 
t1 = t2 + t3 + 100; 

return 0; 
} 

Répondre

8

Parce que l'objet renvoyé par t2 + t3 est const et que vous ne pouvez pas appeler sa fonction non-const (3).

Cela fonctionne très bien dans le cas de "t1 = t2 + 100 + t3;", car l'objet retourné par t2 + 100 est const aussi, mais vous appelez sa fonction const (2), ce qui est correct.

+0

du sens correct ajouter const à suivre fonctionne très bien test const & operator + (int m) const – anand

1
  1. Modifier X pour tester.
  2. Ajoutez un point-virgule à la fin de l'avant-dernière instruction.
  3. Supprimez le const des valeurs de retour de l'opérateur d'addition lorsque vous les modifiez.

Les compiles suivantes:

class test { 
public: 
    test& operator=(const test & other){} // 1 
    test& operator+(const X& other) const {} // 2 
    test& operator+(int m) {} //3 
private: 
    int n; 
}; 

int main() 
{ 
    test t1, t2, t3; 

    t1 = t2 + t3; 
    t1 = t2 + 100; 
    t1 = t2 + 100 + t3; // <-- added a ';' 
    t1 = t2 + t3 + 100; 

    return 0; 
} 
1

Vous avez manqué un const:

const test & operator+(int m) /* ADD CONST HERE */ const {} //3