H
Haochen Xie
Assuming we have class C defined as:
class C {
public:
int x, y;
C operator++() { ++x, ++y; return *this; }
};
So the following line is legal since C is a user defined type:
++C();
But could any one tell me why the following codes are illegal:
void foo(C &c, int val) {
printf("%d, %d\n", c.x, c.y);
c.x = c.y = val;
printf("%d, %d\n", c.x, c.y);
}
int main() {
foo(C(), 8);
}
When I try to compile it with gcc, the compiler complains:
invalid initialization of non-const reference of type 'C&' from an
rvalue of type 'C'
in passing argument 1 of 'void foo(C&, int)'
Is there any reason to make it invalid? And is there any way to pass a
temporary object to a mutable function without a variable to hold it?
class C {
public:
int x, y;
C operator++() { ++x, ++y; return *this; }
};
So the following line is legal since C is a user defined type:
++C();
But could any one tell me why the following codes are illegal:
void foo(C &c, int val) {
printf("%d, %d\n", c.x, c.y);
c.x = c.y = val;
printf("%d, %d\n", c.x, c.y);
}
int main() {
foo(C(), 8);
}
When I try to compile it with gcc, the compiler complains:
invalid initialization of non-const reference of type 'C&' from an
rvalue of type 'C'
in passing argument 1 of 'void foo(C&, int)'
Is there any reason to make it invalid? And is there any way to pass a
temporary object to a mutable function without a variable to hold it?