本 Wiki 开启了 HTTPS。但由于同 IP 的 Blog 也开启了 HTTPS,因此本站必须要支持 SNI 的浏览器才能浏览。为了兼容一部分浏览器,本站保留了 HTTP 作为兼容。如果您的浏览器支持 SNI,请尽量通过 HTTPS 访问本站,谢谢!
这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录前一修订版后一修订版 | 前一修订版 | ||
cs:programming:cpp:courses:cpp_basic_deep:chpt_4 [2024/10/02 14:05] – [其他操作符] codinghare | cs:programming:cpp:courses:cpp_basic_deep:chpt_4 [2024/10/03 06:03] (当前版本) – [sizeof] codinghare | ||
---|---|---|---|
行 135: | 行 135: | ||
</ | </ | ||
<WRAP center round info 100%> | <WRAP center round info 100%> | ||
- | entity: unparenthesized id-expression or an unparenthesized class member access expression. | + | Entity: **unparenthesized id-expression** or an **unparenthesized class member access expression**. |
</ | </ | ||
===类型转换=== | ===类型转换=== | ||
行 359: | 行 359: | ||
{ | { | ||
Str a; | Str a; | ||
- | // 返回左值 | + | // a 是左值,返回左值 |
a.x; | a.x; | ||
- | //(*ptr).x; | + | |
+ | Str().x; | ||
+ | | ||
ptr->x; | ptr->x; | ||
} | } | ||
</ | </ | ||
+ | ==三元条件操作符== | ||
+ | <code cpp> | ||
+ | // 只会求值一个分支 | ||
+ | true ? 3:5; | ||
+ | // 条件表达式返回的类型必须相同 | ||
+ | ture ? 1: " | ||
+ | // 都是左值,则返回左值,否则返回右值 | ||
+ | int x = 0; | ||
+ | false ? 1 : x; // 返回右值 | ||
+ | // 右结合 | ||
+ | // 先判断 score == 0 | ||
+ | int score = 100; | ||
+ | int res = (score > 0) ? 1: (score == 0) ? 0:-1; | ||
+ | </ | ||
+ | ==逗号操作符== | ||
+ | * 典型应用: | ||
+ | * for 循环中可以写出较为复杂的语句 | ||
+ | * 元编程:折叠表达式,包展开 | ||
+ | * 函数的参数表达式不是逗号操作符,参数列表求值顺序不定 | ||
+ | <code cpp> | ||
+ | // 确保操作数从左向右求值 | ||
+ | // 求值结果为右算子 | ||
+ | 2, 3; // result is 3 | ||
+ | // 左结合 | ||
+ | // (2, 3) , 4 | ||
+ | 2, 3, 4; | ||
+ | </ | ||
+ | ==sizeof== | ||
+ | * 返回类型 / 对象 / 表达式返回值占用的字节数 | ||
+ | <code cpp> | ||
+ | int x; | ||
+ | // 推荐统一使用带括号的形式 | ||
+ | sizeof(int); | ||
+ | sizeof(x); | ||
+ | // 对表达式评估时,不会真正执行求值 | ||
+ | int* ptr = nullptr; | ||
+ | // 等价 sizeof(int) | ||
+ | sizeof(*ptr); | ||
+ | </ | ||
+ | ==域操作符== | ||
+ | 用于访问域内的变量 | ||
+ | <code cpp> | ||
+ | int = x; | ||
+ | namspace ABC | ||
+ | { | ||
+ | int x; | ||
+ | } | ||
+ | int main() | ||
+ | { | ||
+ | int x; | ||
+ | int y = x; // local | ||
+ | int y = ::x; // global | ||
+ | int y = ABC::x // ABC | ||
+ | } | ||
+ | </ | ||
+ | ===C++17表达式求值顺序=== | ||
+ | * 之前的限定求值:逗号,三元条件,逻辑与 / 或(短路) | ||
+ | * C++17 新引入的限定 | ||
+ | <code cpp> | ||
+ | // 先求 e1,再求 e2 | ||
+ | e1[e2]; | ||
+ | e1.e2; | ||
+ | e1.*e2; | ||
+ | e1->*e2; | ||
+ | e1<< | ||
+ | e1>> | ||
+ | e2=e1 / e2+=e1/ e2*=e1; | ||
+ | </ | ||
+ | * newType(e) 会先分配内存再求值 |