operator, or comma operator?

By deafult in C++, the comma operator allows you to perform calculations where only an expression is expected:
6
7
8
int x = 3;
cout << (x += 2, x *= 4, x - 2) << endl;
cout << x << endl;
18
20


But how does the compiler know I want this behavior and not that I am passing parameters to a function? Furthermore, what happens when you use a class that has overloaded operator, ? Which comma does the compiler use?

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
struct Comma //Bad example class
{
	short Small;
	long Tall;

	Comma(){}
	Comma(short small, long tall) : Small(small), Tall(tall) {}
	~Comma(){}

	Comma& operator+=(long er)
	{
		Tall += er;
		return((*this));
	}
	Comma& operator-=(short est)
	{
		Small -= est;
		return((*this));
	}
	Comma& operator,(int o)
	{
		Small += o;
		Tall *= o;
		return((*this));
	}
};
274
275
Comma comma (7, 14);
cout << (comma += 6, comma -= 2, comma.Small + Comma.Tall) << endl;


Guess what? I get some crazy errors. Try it yourself. So, is there a way I can force this to work one way or the other based on what I want it to do? Or do I just have to do it the long way around?

By the way, this is only an experiment; I'm not actually going to try and use this code at all.
1
2
Comma comma (7, 14);
(comma += 6, comma -= 2, comma.Small + comma.Tall);


http://www.fredosaurus.com/notes-cpp/oop-friends/overload-io.html

[edit]
Just want to add more.
1
2
3
4
5
6
7
8
9
10
11
12
ostream& operator<< (ostream& out, Comma& c)
{
    out << "Small: " << c.Small << " Tall: " << c.Tall;
    return out;
}

int main()
{
    Comma comma (7, 14);
    cout << (comma += 6, comma -= 2, comma.Small + comma.Tall) << endl;
    return 0;
}


edit
updated the 404 link.
Last edited on
The link you posted is a 404, so I don't understand your response. Also, I meant for the code there to output the sum of Small and Tall, which should by then be 25. Hoever, because the addition and subtraction both return the class itself, it may think I am calling operator, !
Last edited on
Topic archived. No new replies allowed.