当一个对象被用作右值的时候,用的是对象的值(内容),被用作左值时,用的是对象的身份(在内存中的位置);
在取余运算中,如果m%n不等于0,则它的符号和m相同,即m%(-n)等于 m%n, (-m)%n等于 -(m%n)
除非必须,否则不用递增递减运算符的后置版本
解引用优先级的运算符大于点运算符,所以p->fun()等同于(*p).fun(),此处需加括号,*p.fun()表达错误
sizeof
(1)sizeof运算符并不实际计算其运算对象的值,在sizeof元素运算中解引用一个无效的指针仍然是一种安全的行为;
(2)对引用类型执行sizeof运算得到被引用对象所占空间大小;
(3)对string或vector操作只返回该类型固定部分的大小;
(4)当应用于类类型时,其结果是该类的对象的大小与这种对象放入数组时所需的额外填充的大小的总和;
(5)当应用于空类时,总是返回 1,这个1byte是编译器插进去的一个char,这使得这一class的两个object得以在内存中分配独一无二的地址(可以区分开来);
(6)不进行左值向右值、数组向指针和函数向指针的转换#include <iostream> struct Empty {}; struct Base { int a; }; struct Derived : Base { int b; }; struct Bit { unsigned bit: 1; }; //使用unsigned int中一位,只能被赋值为1或0 int main() { Empty e; Derived d; Base& b = d; Bit bit; int a[10]; std::cout << "size of empty class: " << sizeof e << '\n' << "size of pointer : " << sizeof &e << '\n' // << "size of function: " << sizeof(void()) << '\n' // 错误 // << "size of incomplete type: " << sizeof(int[]) << '\n' // 错误 // << "size of bit field: " << sizeof bit.bit << '\n' // 错误 << "size of array of 10 int: " << sizeof(int[10]) << '\n' << "size of array of 10 int (2): " << sizeof a << '\n' << "length of array of 10 int: " << ((sizeof a) / (sizeof *a)) << '\n' << "length of array of 10 int (2): " << ((sizeof a) / (sizeof a[0])) << '\n' << "size of the Derived: " << sizeof d << '\n' << "size of the Derived through Base: " << sizeof b << '\n' << "size of the bit: " << sizeof bit << '\n'; //以下为运行结果,Dev-C++ GCC 4.8.2 64-bit /* size of empty class: 1 size of pointer : 8 size of array of 10 int: 40 size of array of 10 int (2): 40 length of array of 10 int: 10 length of array of 10 int (2): 10 size of the Derived: 8 size of the Derived through Base: 4 size of the bit: 4 */ }
无符号类型不小于带符号类型,带符号类型转换成无符号,无符号类型小于带符号类型,若无符号类型的所有值都可以存在该带符号类型中,则无符号->带符号,否则,带符号->无符号
命名的强制类型转换:(应尽量避免在程序中使用强制类型转换)
(1)static_cast:任何具有明确定义的类型转换,只要不包含底层const,都可以使用;将较大算数类型赋值给较小数据类型时非常有用,static_const告诉编译器和读者,我们并不在乎潜在的精度损失int i,j; i = 3, j = 2; // 注意,此处只是将j强制转换为double double slope = static_cast<double>(j)/ i; // 0.666667
(2)const_cast只能改变运算对象额度底层const,“去掉const性质”,将常量指针转化成非常量
const char* pc; char* p = const_cast<char*>(pc); //正确,但通过p写值是未定义行为
(3)reinterpret_cast:为运算对象的位模式提供较低层次上的重新解释
c++ primer 笔记,第四章
最新推荐文章于 2024-08-04 16:33:29 发布