与C对比:
#define NULL(void *) 0
C中的空指针为NULL C++中的空指针则定义为宏
#define NULL 0
当在C++中需要定义我们的指针为空时,不要使用NULL,使用nullptr,否则容易出现二义性
void func(char * p){}
void func(int x) {}
int main()
{
func(NULL);//此时在C++中认为调用的是func(int x) 因为在C++中认为NULL是0
}
此时应该使用 关键字 func(nullptr);//调用 func(char *p) nullptr是指针为空的常量值
注意:
1.nullptr是C11新引入的关键字,是一个所谓“指针空值类型”的常量,在C++程序中直接使用
2.在C11中,sizeof(nullptr)与sizeof((void *)0) 所占的字节数相同都(4或8)。
3.为了提高代码的健壮性,在后续表示指针建空值时,建议最好使用nullptr。
根据以上当比较指针是否为空时,可以这样写:
typedefint *p=nullptr;
if(p==nullptr); //是正确的
using也是重命名规则: using与template结合typedef unsigned int u_int;
typedef char* pstr;
typedef const char* str;
typedef int Array[10]; //Array 指的是int [10]的数组类型
typedef void (*pfun)(int,int); //pfun指的是返回值为0,形参值为int,int的函数类型
typedef struct ListNode
{
int data;
struct ListNode* next;
}ListNode,* LinkList;
template
//默认值 using Array=T[N];
int main()
{
Array<>a;
Array
ar; Array
dx; Array
cpar; return 0;
}
小点:函数的声明和定义
int add(int,int); //声明
int add(int a,int b) //定义
{
return a+b;
}
int main()
{
add(12,23); // add();
add;
int (* pfun)(int,int)=&add //或者add,都表示函数的地址
}
注意:函数名有四个作用 声明、定义、调用、地址
如果使用using重命名的话
c++中的字符串表示using pfun=int(*)(int,int); //一个函数指针
pfun p=&add;
首先c++中表示字符串时,就不需要字符串数组来表示。在此引入字符串库
#include
//与#include 不同,后者是字符串函数库
与C对比:
char stra[]={"yhping"};
int n=strlen(stra);
printf("%sn",stra) ;
for(int i=0;i
{
if(stra[i])
{
}
}
strcat(stra,"hello"); //此时无法连接 stra[]的长度只有7 如果连接会越界
此时就需要c++中的字符串库的方法就非常方便:
using namespace std;
int main()
{
std::string stra ="yhping";
cout<
int n=stra.length(); //和 n=stra.size(); 相同都是用来计算当前字符串的字符个数
for(int i=0;i
{
cout<
}
cout <
char *p=stra.data(); //可以获得字符串的首地址 可以通过该地址改变字符串的值
const char *cp=stra.c_str(); //也可以获得字符串的首地址, 但是是常性的 不可以修改字符 串内容
}
判断字符串是否为空
using namespace std;
int main()
{
std::string stra="yhping";
std::string strb="hello";
std::string strc;
cout<
cout<
cout<
cout<
return 0;
}
两个字符相加相连接
using namespace std;
int main()
{
std::string stra="yhping";
std::string strb="hello";
std::string strc;
strc=stra+' '+strb;//可以按照普通的变量相加的规则 非常灵活
cout<
return 0;
}
sizeof(strc):
std::string strc;
strc="yhp"
cout<
cout<
思考:为什么会不一样?
因为与结构体中的变量相同,sizeof()时单纯指这个变量所占字节,不是变量所指向空间的大小
using namespace std:
int main()
{
std::string stra;
for(int i=0;i<20;++i)
{
cout<<"sizeof(stra): "<
stra+="yhpinghello";
cout<
cout<
}
}//执行后 sizeof(stra)不变都是28 后两个输出会发生改变



