C++学习
new delete
使用方法:
int *p =new int[10];
内联函数
介于宏函数和普通函数之间
宏函数优点:代码内嵌,避免了函数调用,不会压栈和出栈。
宏函数缺点:容易产生歧义,易使程序的text段体积过大,不会进行类型检查。
普通函数优点:一段高度抽象的逻辑,避免重复,不易产生歧义,使text段体积变小,会类型检查。
普通函数缺点:增加函数调用的压栈出栈开销。
内联函数融合了两者的优点。系统会自动判断函数是否可以为inline,所以inline使对编译器的一个建议。一般函数在10行之内的情况下或频繁调用情况下才会声明为inline。
强转
使用方法
c语言的强转
type a = (type)b;
C++强转
static_cast 对隐式类型转化的,可用此类型
reinterpret_cast 对于无隐式类型的转化,static_cast 已经不可用
const_cast 脱常,只能用于指针和引用
dynamic_cast
例子:
float a = 5.6;
int b =5;
b = static_casta;
a = static_castb;
void *p;
int q;
p=q;//正确
q=p;//错误
q = static_cast<int>§;//正确
int x =10;
int y = 3;
float z = x/y;//结果是3
float z = static_cast(x/y);//结果是3.333
char pc = static_cast<char>(malloc(100));//
char p; int q;
p =reinterpret_cast<char>(q);//正确
int p = (reinterpret_cast<int>)(reinterpret_cast(a) +1);//正确
intp = (int)((int)(a)+1);//错误
void fun2(int &v)
{
}
const int a =19;
int &ra = const_cast<int&>(a);
const结论:
我们可以改变const自定义类的成员变量,但对于内置数据类型,却表现为未定义行为。
宏在预处理的时候发生替换,const 在编译阶段发生替换
命名空间
用于大型项目开发
namespace 是对全局命名空间的划分
string 字符串
属于标准库;
string不是关键字,是一个类;
string封装了一个char类型,sizeof(string)=4;
string 类型不存在溢出;
初始化可以一下两种格式
string str =“dsfasdfasdf”;
string str2(str);
string可以用’+‘拼接;
str3 = str1+str2;
也可以用‘’来判断两字符串是否相等;
if(str1str2)
也可以用’<‘或’>'判断大小;
因为C++完全兼容C语言,将字符串拷贝到buffer里面时,使用
strcpy(buffer,str.c_str());
c_str()函数将string类型转变为C语言类型的char;
swap()函数交换string;
find(s,0)函数返回从0位置开始,第一次出现s的下标,找不到返回-1;