FAQ 23.03 What operators can't be overloaded?The only C++ operators that can't be overloaded are dot (.), .*, arithmetic if (?:), size (sizeof), typeid, and ::. Here's an example of an array-like class without operator overloading. class Array { public: int& elem(unsigned i) throw(out_of_range); protected: int data_[100]; }; inline int& Array::elem(unsigned i) throw(out_of_range) { return data_[i]; } void sample() { Array a; a.elem(10) = 42; a.elem(12) = 10; a.elem(12) += a.elem(10); } The member function elem(unsigned) returns a reference to the ith element of the Array. A better solution, one whose user syntax is more intuitive, would replace elem with operator[]: class Array2 { public: int& operator[] (unsigned i) throw(out_of_range); protected: int data_[100]; }; inline int& Array2::operator[] (unsigned i) throw(out_of_range) { return data_[i]; } void sample2() { Array2 a; a[10] = 42; a[12] = 10; a[12] += a[10]; } int main() { sample(); sample2(); } |