Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When I saw the tags "c++" and "operator overloading", my mind alarm turns ON.</p> <p>C++ operator overloading is complex, and some operators like "()" or "->" make it more difficult.</p> <p>I suggest, before overloading operators, making either a global function or method with the same purpouse, test it works, and later replace it with the operator.</p> <p>Global friend function example:</p> <pre><code>class c { private: int n[10]; public: c(); ~c(); // int operator()(int i) { return n[i]; } // there is a friend global function, that when receives a "c" object, // as a parameter, or declares a "c" object, as a local variable, // this function, will have access to the "public" members of "c" objects, // the "thisref" will be removed, when turned into a method friend int c_subscript(c thisref, int i) ; }; int c_subscript(c* thisref, int i) { return c-&gt;n[i]; } int main() { c* objC() = new c(); // do something with "objcC" int x = c_subscript(objC, 3); // do something with "x" return 0; } // int main(...) </code></pre> <p>Local function ( "method" ) example:</p> <pre><code>class c { private: int n[10]; public: c(); ~c(); // int operator()(int i) { return n[i]; } int subscript(int i) ; }; int c::subscript(int i) { return this.n[i]; } int main() { c* objC() = new c(); // do something with "objcC" int x = c-&gt;subscript(objC, 3); // do something with "x" return 0; } // int main(...) </code></pre> <p>And, finally use the overloaded operator:</p> <pre><code>class c { private: int n[10]; public: c(); ~c(); int subscript(int i) ; int operator()(int i) { return this.subscript(i); } }; int c::subscript(int i) { return this.n[i]; } int main() { c* objC() = new c(); // do something with "objcC" int x = c-&gt;subscript(3); // do something with "x" int x = c(3); // do something with "x" return 0; } // int main(...) </code></pre> <p>Note that in the final example, I keep the method with a unique identifier.</p> <p>Cheers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload