c++ - object.function().function().function()....... how does this work? -


i have problem understanding how c++ syntax works.

#include<iostream> using namespace std;  class accumulator{ private:     int value; public:     accumulator(int value){this->value=value;}     accumulator& add(int n){value+=n;}     int get(){return value;}; };  int main(int argc, char* argv[]){     accumulator acc(10);     acc.add(5).add(6).add(7); //<-----how work?????     cout<<acc.get();     return 0; } 

this line: acc.add(5).add(6).add(7); work left right or other way acc.add(5) first , add(6) dont it.

result supposed 28.

thanks in advance.

edit: weird, code gets compiled without errors on g++. got code non-english college c++ textbook. english not first language.

2nd edit: desired warnings after using -wall option.

your code doesn't compile, if did, work left right. add returns reference accumulator (it doesn't have return value in code, should return *this) after call

acc.add(5) 

the return value reference acc, can call add on again.

here modified example mult added shows order of operations:

#include <iostream> using namespace std;  class accumulator{ private:     int value; public:     accumulator(int value){ this->value = value; }     accumulator& add(int n){ value += n; return *this; }     accumulator& mult(int n){ value *= n; return *this; }     int get(){ return value; }; };  int main(int argc, char* argv[]){     accumulator acc(10);     acc.add(5).add(6).mult(7);     cout << acc.get();     return 0; } 

if right left, result 81, left right , result 147.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -