c+ - Quelles sont les règles de base et les idiomes pour le surcharge'opérateur

Mots clés : c++operatorsoperator-overloadingc++-faqc++

meilleur 3 Réponses c+ - Quelles sont les règles de base et les idiomes pour le surcharge'opérateur

vote vote

92

X& X::operator=(X rhs) {   swap(rhs);   return *this; } 
std::ostream& operator<<(std::ostream& os, const T& obj) {   // write obj to stream    return os; }  std::istream& operator>>(std::istream& is, T& obj) {   // read obj from stream    if( /* no valid object of T found in stream */ )     is.setstate(std::ios::failbit);    return is; } 
class foo { public:     // Overloaded call operator     int operator()(const std::string& y) {         // ...     } }; 
foo f; int a = f("hello"); 
inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ } inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);} inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ } inline bool operator> (const X& lhs, const X& rhs){return  operator< (rhs,lhs);} inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);} inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);} 
bool operator<(const X& rhs) const { /* do actual comparison with *this */ } 
class X {   X& operator++()   {     // do actual increment     return *this;   }   X operator++(int)   {     X tmp(*this);     operator++();     return tmp;   } }; 
class X {   X& operator+=(const X& rhs)   {     // actual addition of rhs to *this     return *this;   } }; inline X operator+(X lhs, const X& rhs) {   lhs += rhs;   return lhs; } 
class X {         value_type& operator[](index_type idx);   const value_type& operator[](index_type idx) const;   // ... }; 
class X {   value_type& operator[](index_type idx);   value_type  operator[](index_type idx) const;   // ... }; 
class my_ptr {         value_type& operator*();   const value_type& operator*() const;         value_type* operator->();   const value_type* operator->() const; }; 
vote vote

84

enum Month {Jan, Feb, ..., Nov, Dec} 
vote vote

78

class my_string { public:   operator const char*() const {return data_;} // This is the conversion operator private:   const char* data_; }; 
void f(const char*);  my_string str; f(str); // same as f( str.operator const char*() ) 
void f(my_string&); void f(const char*);  f(my_string()); 
class my_string { public:   explicit operator const char*() const {return data_;} private:   const char* data_; }; 
 prog.cpp: In function ‘int main()’: prog.cpp:15:18: error: no matching function for call to ‘f(my_string)’ prog.cpp:15:18: note: candidates are: prog.cpp:11:10: note: void f(my_string&) prog.cpp:11:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘my_string&’ prog.cpp:12:10: note: void f(const char*) prog.cpp:12:10: note:   no known conversion for argument 1 from ‘my_string’ to ‘const char*’ 

Questions similaires