结构体区别
使用时,类型上可以省略struct关键字,直接用结构体名即可。
c++中结构体中允许函数存在。
struct Students{
char name[20];//属性(特征)、数据成员
int num;
void print();{//行为(方法)、成员函数
cout<<name<<"\t"<<endl;
}
}//若要在结构体外定义函数需要用命名空间限定。
/*void Students::print(){
cout<<name<<"\t"<<endl;
}*/
调用结构体方法,和数据成员方式时一样的
对象(结构体变量).成员
对象指针->成员
(*对象指针).成员
C++在没有写构造函数和权限限定的时候,用法和C语言的用法是一样
动态内存申请
C语言的动态内存申请
malloc 不带初始化 ,calloc 带初始化,realloc重新申请,free 释放
c++中动态内存申请
申请:new
释放:delete
单个变量内存申请
char* pChar=new char;
*pChar=’A‘;
delete pChar;
pChar=nullptr;
带初始化的
char* pChar=new char(’A’);
数组
void testArrayMemory()
{
//一维数组
//1.不带初始化
//长度可以是变量,只要值就可以
int* pInt = new int[3]; //等效产生了int pInt[3]的数组
//const char* pstr = new char[15]; //你 --->大老婆
//const char* pstr1 = pstr; //朋友--->大老婆
//pstr = "ILoveyou"; //你-->二老婆,改变了你的指向,但没有影响到朋友(pstr1)的指向
char* pstr = new char[15];
strcpy_s(pstr, 15, "ILoveyou");
cout << pstr << endl;
//cout << pstr1 << endl;
//带初始化的 一堆数据用 {}
int* pNum = new int[3]{ 1,2,3 };
for (int i = 0; i < 3; i++)
{
cout << pNum[i] << " ";
}
cout << endl;
delete[] pNum;
char* str = new char[20]{ 'A','B','\0' };
cout << str << endl;
delete[] str;
str = nullptr;
str = new char[20]{ "ILoveyou" };
cout << str << endl;
delete[] str;
str = nullptr;
delete [] pInt; //数组的释放 不需要大小
//释放只有两种形式 delete 指针 delete [] 指针
//delete [][] p 没有这种写法
pInt = nullptr;
}
struct MM
{
char* name;
int age;
//成员函数
void printMM()
{
cout << name << "\t" << age << endl;
}
};
void testStructMemory()
{
//new一个对象
int* p = new int(23);
//结构体只能用大括号
MM* pMM = new MM;
//结构体中指针,要做二次申请,才能strcpy,或者赋值
pMM->name = new char[20];//结构体中有指针,使用的时候还需要二次申请内存。
strcpy_s(pMM->name,20, "丽丝");
pMM->age = 188;
pMM->printMM();
//申请顺序和释放顺序是相反
delete[] pMM->name;
delete pMM;
}
int main()
{
//testOneMemory();
//testArrayMemory();
testStructMemory();
return 0;
}
内存池
允许申请一段内存,供程序使用,综合管理内存
(注:c语言中malloc的内存在堆区,c++中new的内存在自由存储区)
#include<iostream>
using namespace std;
void allocateMemory{
char* SumMemory=new char[1024]; //分配这个总内存
int* pNum=new(SumMemory)int[3]={1,2,3};
char* pStr=new(SumMemory+12)char[20];//char* pStr=new(pNum+3)char[20]={"ILoveYou"};
for(int i=0;i<3;i++){
cout<<pNum[i]<<endl;
}
delete[] SumMemory;
SumMemory=nullptr;
}
C++string类型
c++如果转换成c语言的char*
或者data()函数
c++中记录字符串长度没有把\0算入。所以打印不能用%s打印。