int a=5;
++a=a;
Please find the above code segment. The code is ok for the c++(g++) compiler but shows error while using c (gcc) compiler. May I know the reason for this? The error in c compiler is "lvalue required as left operand of assignment".
There is operator overloading in C++ (and you can overload pre-increment also), so to achieve some additional goals pre-increment operator returns lvalue in C++.
For example:
Your class may implement some pointer functionality and may need:
Pre-increment may be useful in this case.
Abstract code example:
class MyIntPtr {
int *val;
...
public:
MyIntPtr(int *p) { ... };
MyIntPtr &operator++() { ++val; return *this; };
void operator=(int i) { *val = i; }
...
};
...
int array[10];
MyIntPtr ptr(array);
for(int i = 0; i < sizeof array; ++i)
++ptr = i;
因为在C ++中,preincrement运算符产生左值,而在C中,它是rvalue。
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.