C++基础知识

基础知识

  1. &&和||具有“短路”特性,特别是在第二个操作数有++或--时要注意
  2. 显式类型转换
    • (类型说明符)表达式 //C风格的
    • 类型说明符(表达式) //cpp风格的
    • const_cast<>()
    • static_cast<>() //基本类型都可用这种来强转
    • reinterpret_cast<>()
    • dynamic_cast<>()
  3. 内联函数不是在函数调用时发生转移,而是在编译时将函数嵌入在每一个调用处。语法:函数定义前用inline修饰。
  4. 带默认形参值的函数。
    • 默认值的形参在形参列表的最后。
    • 相同的作用域内,不允许在同一个函数的多个声明中对统一参数的默认值重复定义。

void foo(int a = 4,int b = 3);
void foo(int a /* = 4 /,int b / = 3 */)
{
}


5. 函数重载 。具有相同函数名,但是**形参类型和个数不同**。
6. 函数递归
递归函数即自调用函数,在函数体内部直接或间接地自己调用自己,即函数的嵌套调用是函数本身。
```cpp
unsigned fac(unsigned n)
{
  unsigned f;
  if(n == 0)
      f = 1;
  else
      f = fac(n - 1) * n;
  return f;
}

要注意递归函数的调用方式。分为两部分,递推和回归。

  • 递推。不断拆解问题的过程,从未知到已知,最终到达已知的条件结束递推。
  • 回归。从已知出发,逐一求值回归,达到递推开始处,结束回归阶段,完成递归调用。

特别要注意有IO操作的递归函数。 比如说利用递归来输出数组中的每个元素,结果一定是倒序的。

  1. 对象生存期
  • 静态生存期(static)。与程序运行期相同。基本类型,默认初值为0。在局部作用域中只初始化一次。
  • 动态生存期。与块同期。
    练习:
#include <iostream>
using namespace std;
int i = 1;
void other()
{
static int a = 2;
static int b;
int c = 10;
a += 2;
i += 32;
c += 5;
cout<<"----other----"<<endl;
cout<<"i:"<<i<<"a:"<<a<<"b:"<<b<<"c:"<<c<<endl;
}
int int main(int argc, char const *argv[])
{
static int a;
int b = -10;
int c = 0;
 
 
cout<<"----main----"<<endl;
cout<<"i:"<<i<<"a:"<<a<<"b:"<<b<<"c:"<<c<<endl;
c += 8;
 
 
other();
cout<<"----other----"<<endl;
cout<<"i:"<<i<<"a:"<<a<<"b:"<<b<<"c:"<<c<<endl;
 
 
i += 10;
other();
cout<<"----other----"<<endl;
cout<<"i:"<<i<<"a:"<<a<<"b:"<<b<<"c:"<<c<<endl;
return 0;
}
结果:
----main----
1 0 -10 0
----other----
33 4 0 15
----main----
33 0 -10 8
----other----
75 6 4 15
  1. 字符串
  • C字符串(const char*)
  • C++ string类
原文地址:https://www.cnblogs.com/Sinte-Beuve/p/4803546.html