C++ Primer 笔记 三

本文深入探讨了C++中的数组定义与使用方法,包括数组作为函数参数的行为、数组与指针的关系、引用如何帮助避免不必要的复制,以及数组在不同上下文中的自动转换规则。
arrays
函数内部定义的array 初始值不定
int a1[]={1 ,2,3}   ok
auto a2(a1);   a2 is an int *points to the first element in a1
decltype(a1)a3 = {5,6,7}
decltype(a1) return  array of 3 ints

pointers are iterators
but array is not class no members

sstddef  header
type  size_t   ptrdiff_t   machine specific
unlike subsxripts for vector and string, the index of the built-in subscript operators is not an unsigned type.
string s("hello world");
char *sstr=s;// error
const char *sstr = s.c_str();//ok
但要用的话必须及时拷贝出去 因为任何对s的修改都有可能更改内容
用array给vector赋值
int a_int = {1,2,3,4,5}
vector<int> subV(a_int+1,a_int+4)
a[1] to a[3]赋值进去了
vector<int> subV(begin(a_int),end(a_int))


using int_array = int[4];
typedef int int_array[4];
把 int_array 定义为 int [4]


a[m][n]
for(auto &row :a)  ok
row is a reference  and should be

for(auto row: a)  error  row is a int *

when we use an array it is automatically converted to a pointer to its  first element.



decltype(  a)
若为左值的话 返回引用类型
啊a为 *p  返回int&

m/n   m%n
除法  分子分母负号都提前
取余  分子负号忽略 分母提前

reference的好处避免了数值的拷贝
++i  优与 i++  对指针 整数编译器有优化 但对iterator 未必

<< 是左结合的 被重载为 IO或移位操作

最好用double 最次和float一样efficient 精度高很多

int j
static_cast<double>(j)
static 适用于无lowlevel const的情形

const char* pc;
char *p = const_cast<char *>(pc)
ok but writing *p is undefined! !
例如编译时通过 修改时报错 段核心已转储

char *p = static_cast<char *>(pc)    //    static_cast  不能改变 constness   error! can not cast away const
static_cast<string>(pc)   //ok!  convert string literal to string
 

const_cast<string>(pc)  不懂p164   error  const_cast only change constness   不再改变类型

const只能改变constness 若再更改为其他类型就会报错!
 更改为其他类型就不是只改变constness了 
type也会变 存储空间也会变了

old style casts
type(expr)
(type )expr
不会报任何问题



定义在 控制流内的变量是私有的
switch里面
不允许越过jump 有initialize 的语句

例如 string  str; implicitly 初始化
int i=1;  explicitly 初始化
error!!!!
声明和赋值要分开
可以{      }来解决

variable defined in a while condition or while body are created and destroyed on each iteration.



using reference to avoid copies
c++中多用引用来代替指针



const int &a=42;  ok


void 函数也可以return 的例如 return foo()  其中foo为void函数

还可以return reference

返回return初始化不能带 narrowing conversion  由精度高变精度低的不行

auto func()->int(*)[10]   等价
int *(func()) [10]



high level 不可以重载
low level 可以重载

函数名和变量名重名会有危险吗?

函数默认参数
string screen(int h=foo(),wz=30,char = c)
只要 foo() c之前出现过且类型(可经转换后)匹配

function type is automatically treated as a pointer to function
when used as parameters
function type and pointer to function are slightly different




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值