【C++ Primer Chapter 4 & 5 总结】C++ 表达式 && 语句

1.C++中的表达式要么是左值(lvalue)要么是右值(rvalue)。
2.当我们使用一个对象作为右值,我们使用的是该对象的值(its contents),当我们使用一个对象作为左值,我们使用的是对象的标识(identity,its location in memory)。
3.我们可以在需要rvalue的时候用lvalue,但是不能在需要lvalue的时候用rvalue。
4.当使用decltype时,如果表达式得到的是lvalue,则decltype(expression)是引用类型。 e.g.:
int a = 10;
int *p = &a;
decltype(*p) b = a;  //decltype(*p) 是 int&
b = 5;
cout << a << " " << b; // 5 5
 
5.取模运算符:%。如果m%n结果非零,则m%n的符号与m一致。
cout << (21 % -8) << endl;   // 5
cout << (-21 % -8) << endl;  // -5
cout << (21 % 8) << endl;    // 5
cout << (-21 % 8) << endl;   // -5
 
6.赋值运算符的左边操作数一定要是可修改的lvalue。
7.赋值运算符是右结合性的。多次赋值的赋值语句中的每个对象必须具有与其右侧邻居相同的类型,或者该邻居可以转换的类型。
string s1, s2;
s1 = s2 = "OK"; //string literal "OK" converted to string
 
8.++x, --x。自增/减符号在前,操作数加/减1,得到改变后的对象作为其结果。
9.x++, x--。自增/减符号在后,操作数加/减1,但是生成原始对象的一个copy,未变化的对象值作为其结果。
10.符号在前的自增/减返回对象本身作为lvalue,符号在后的自增/减返回对象原始值作为rvalue。
11.左移,右移操作符是左结合性。
cout << "hi" << "there" << endl;      // ((cout << "hi") << "there") << endl;
 
12.sizeof是右结合性的。sizeof结果是一个constant expression。
13.逗号表达式的结果是其最右边的表达式,如果该最右边表达式是lvalue,则整个逗号表达式的结果是lvalue。
14.数组名可以隐式的转为指针类型。但是当1. 用于decltype,或者2. 作为取址符(&),sizeof,或者typeid操作符的操作数,或者3. 初始化一个数组的引用时,该转换会被省略。
int a[10];
int *p = ia;               // ia被转换为指向a第一个元素的指针
 
15.使用cast进行显示的类型转换。
static_cast: 用于除包含低级const以外的任何定义明确的类型转换
const_cast:仅用于操作数的const性质,将cosnt对象转换成非const对象,将非cosnt对象转换成const对象, "cast away the const"。
e.g.: const char *cp;  char *q = static_cast<char*>(cp); 
e.g.: const_cast<const string&>(s1);
cast-name<type>(expression);         // cast-name: static_cast, dynamic_cast, const_cast, reinterpret_cast
char s[] = "abcd";
const char *pc = s;               // const说明不可以通过pc改变s
char *p = const_cast<char*>(pc);
cout << *pc << endl;              // a
cout << *p << endl;               // a
char c = 'b';
*p = c;                      // writing through p is undefined,结果未知?
cout << *pc << endl;              // b
cout << *p << endl;               // b
cout << s << endl;
 
16.C++11新特性。for()语句。
for(declaration : expression)
        statement
// expression 必须是可以遍历的序列,或者有begin(),end()成员函数的对象
//declaration定义了变量。序列中的每个元素必须可以转换成变量类型。最简单的方式是使用auto类型说明符
 
17.C++的跳转语句:break,continue,goto。
goto label;
label:
    return;
 
18.异常。throw...try...catch。throw抛出异常,try...catch解决异常。从try块内执行的代码引发的异常通常由catch子句之一处理。
//和异常有关的头文件
exception
stdexcept
new
type_info
 
原文地址:https://www.cnblogs.com/tristatl/p/14825840.html