简体   繁体   中英

Operator overloading the comma operator in C++

So I have this sample of code:

#include<iostream>
using namespace std;

class a{


    public:
        a(int v){value=v;}
        int value;
        void operator,(a b){
            cout<< this->value<<" "<<b.value<<"\n";
        }
};

int main(){
    a o1(1);
    a o2(2);
    a o3(3);

    o1,o2,o3;

}

And it only prints "1 2" (and not "1 2 3" as I expected). I did some research but nothing made the reason this is happening clear to me. Can someone give me an explanation?

There is a built in comma operator which does not print value of the operands. o1.operator,(o2) prints the desired 1 2 but returns void and then void,o3 uses the built in comma operator.

You can change your code to this to get output closer to the desired one:

    const a& operator,(const a& b) const {
        cout<< this->value<<" "<<b.value<<"\n";
        return b;
    }

Note that this will print

1 2
2 3

To get the desired output is a little more difficult it is much simpler to write

std::cout << o1.value << " "  << o2.value << " " << o3.value;

However, I suppose this whole code is just to illustrate overloading the comma operator. So for the sake of illustration (but not to be used for real code), this is how you can use a proxy that accumulates the output to be printed and prints it via std::cout at the end of the line:

#include <iostream>
#include <sstream>

struct a{
    a(int v){value=v;}
    int value;
    struct proxy {
        std::string out;
        proxy& operator,(const a& b) {
            out += " " + std::to_string(b.value);
            return *this;
        }
        ~proxy(){ std::cout << out << "\n"; }
    };

    proxy operator,(const a& b) const {
        return {std::to_string(value) + " " + std::to_string(b.value)};      
    }
};

int main(){
    a o1(1);
    a o2(2);
    a o3(3);
    a o4(4);
    o1,o2,o3,o4;
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM