C++ Operator Precedence

本文详细介绍了C++中各种运算符的优先级及其结合性,并提供了运算符重载的相关指导。了解这些内容有助于正确地编写和理解复杂的C++表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

The operators at the top of this list are evaluated first. Operators within a group have the same precedence. All operators have left-to-right associativity unless otherwise noted.

 

PrecedenceOperatorDescriptionExampleOverloadableAssociativity
1::Scope resolution operatorClass::age = 2;noleft to right
2()Function callprintf(“Hello world/n”);yesleft to right
()Member initalizationc_tor(int x, int y) : _x(x), _y(y * 10) {}yes
[]Array accessarray[4] = 2;yes
->Member access from a pointerptr->age = 34;yes
.Member access from an objectobj.age = 34;no
++Post-incrementfor (int i = 0; i < 10; i++) cout << i;yes
--Post-decrementfor (int i = 10; i > 0; i--) cout << i;yes
dynamic_castRuntime-checked type conversionY& y = dynamic_cast<Y&>(x);no
static_castUnchecked type conversionY& y = static_cast<Y&>(x);no
reinterpret_castReinterpreting type conversionint const* p = reinterpret_cast<int const*>(0x1234);no
const_castCast away/Add constnessint* q = const_cast<int*>(p);no
typeidGet type informationstd::type_info const& t = typeid(x);no
3!Logical negationif (!done) ...yesright to left
notAlternate spelling for !
~Bitwise complementflags = ~flags;yes
complAlternate spelling for ~
++Pre-incrementfor (i = 0; i < 10; ++i) cout << i;yes
--Pre-decrementfor (i = 10; i > 0; --i) cout << i;yes
-Unary minusint i = -1;yes
+Unary plusint i = +1;yes
*Dereferenceint data = *intPtr;yes
&Address ofint *intPtr = &data;yes
sizeofSize (of the type) of the operand in bytessize_t s = sizeof(int);no
newDynamic memory allocationlong* pVar = new long;yes
new []Dynamic memory allocation of arraylong* array = new long[20];yes
deleteDeallocating the memorydelete pVar;yes
delete []Deallocating the memory of arraydelete [] array;yes
(type)Cast to a given typeint i = (int)floatNum;yes
4->*Member pointer selectorptr->*var = 24;yesleft to right
.*Member object selectorobj.*var = 24;no
5*Multiplicationint i = 2 * 4;yesleft to right
/Divisionfloat f = 10.0 / 3.0;yes
%Modulusint rem = 4 % 3;yes
6+Additionint i = 2 + 3;yesleft to right
-Subtractionint i = 5 - 1;yes
7<<Bitwise shift leftint flags = 33 << 1;yesleft to right
>>Bitwise shift rightint flags = 33 >> 1;yes
8<Comparison less-thanif (i < 42) ...yesleft to right
<=Comparison less-than-or-equal-toif (i <= 42) ...yes
>Comparison greater-thanif (i > 42) ...yes
>=Comparison greater-than-or-equal-toif (i >= 42) ...yes
9==Comparison equal-toif (i == 42) ...yesleft to right
eqAlternate spelling for ==
!=Comparison not-equal-toif (i != 42) ...yes
not_eqAlternate spelling for !=
10&Bitwise ANDflags = flags & 42;yesleft to right
bitandAlternate spelling for &
11^Bitwise exclusive OR (XOR)flags = flags ^ 42;yesleft to right
xorAlternate spelling for ^
12|Bitwise inclusive (normal) ORflags = flags | 42;yesleft to right
bitorAlternate spelling for |
13&&Logical ANDif (conditionA && conditionB) ...yesleft to right
andAlternate spelling for &&
14||Logical ORif (conditionA || conditionB) ...yesleft to right
orAlternate spelling for ||
15? :Ternary conditional (if-then-else)int i = a > b ? a : b;noright to left
16=Assignment operatorint a = b;yesright to left
+=Increment and assigna += 3;yes
-=Decrement and assignb -= 4;yes
*=Multiply and assigna *= 5;yes
/=Divide and assigna /= 2;yes
%=Modulo and assigna %= 3;yes
&=Bitwise AND and assignflags &= new_flags;yes
and_eqAlternate spelling for &=
^=Bitwise exclusive or (XOR) and assignflags ^= new_flags;yes
xor_eqAlternate spelling for ^=
|=Bitwise normal OR and assignflags |= new_flags;yes
or_eqAlternate spelling for |=
<<=Bitwise shift left and assignflags <<= 2;yes
>>=Bitwise shift right and assignflags >>= 2;yes
17throwthrow exceptionthrow EClass(“Message”);no 
18,Sequential evaluation operatorfor (i = 0, j = 0; i < 10; i++, j++) ...yesleft to right

 

 

 

One important aspect of C++ that is related to operator precedence, is the order of evaluation and the order of side effects in expressions. In most circumstances, the order in which things happen is not specified. For example in f() + g() whether f() or g() is called first is not specified. If at least one of the functions has side effects the results may differ across compilers, different versions of the same compiler or even between multiple runs of the same compiler.

Further, the effect of certain expressions is undefined. For example, consider the following code:

    float x = 1;
    x = x / ++x;

The value of x and the rest of the behaviour of the program after evaluating this expression is undefined. The program is semantically ill-formed: x is modified twice between two consecutive sequence points.

Expressions like the one above must be avoided. When in doubt, break a large expression into multiple statements to ensure that the order of evaluation is correct.

Overloading of operators can be very useful and very dangerous. On one hand overloading operators for a class you have created can help with logistics and readability of code. On the other hand you can overload an operator in such a way that it can either obfuscate or just downright break your program. Use carefully. In particular never overload &&|| or ,. In the overloaded context they lose the guarantee that the left operand is evaluated before the second and that there is a sequence point inbetween.

There are two ways to over load an operator: global function or class member.

Example of overloading with a global function:

     ostream& operator <<(ostream& os, const myClass& rhs);

But to be able to reach any private data within a user defined class you have to declare the global function as a friend within the definition of the class.

Example:

     class myClass {
 
       // Gives the operator << function access to 'myData'
       // (this declaration should not go in public, private or protected)
       friend ostream& operator <<(ostream& lhs, const myClass& rhs);
 
       private:
         int myData;
     }

Overloading with a class member can be done as follows:

     class myClass {
 
       public:
         // The left hand side of this operator becomes '*this'.
         int operator +(const myClass& rhs);
 
       private:
         int myData;
     }

 

原文:http://www.cppreference.com/wiki/operator_precedence

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值