075 动态内存 new和delete
void test07() {
int *p = NULL;
// 从堆区申请
p = new int;
*p = 100;
cout<<"*p="<<*p<<endl;//100
// 释放空间
delete p;
// new申请空间同时初始化空间
int *p1 = NULL;
p1 = new int(100);
cout<<"*p1="<<*p1<<endl;//100
delete p1;
}
int main(int argc,char *argv[])
{
test07();
return 0;
}
077 结构体变量
结构体中的成员拥有独立的空间
不初始化结构体成员就使用 运行结果是没有意义的
lucy是一个局部的结构体变量 不初始化 变量中的成员内容不确定
清空结构体变量
#include<string.h>
// 清空整个结构体变量memset
void test02() {
Student lucy;
memset(&lucy,0,sizeof(lucy));
cout<<lucy.age<< " " << lucy.name<<endl;
}
int main(int argc,char *argv[])
{
test02();
return 0;
}
运行结果
再看字符数组的赋值
#include <iostream>
#include<string.h>
using namespace std;
// 结构体测试
struct Student {
int age;
char name[32];
};
void test01() {
Student lucy;
lucy.age = 100;
// name成员 位符号常量 不允许用=给name赋值
strcpy(lucy.name,"lucy");
cout<<lucy.age<< " " << lucy.name<<endl;
}
int main(int argc,char *argv[])
{
test01();
return 0;
}
运行结果如下
078 结构体变量的赋值
079 结构体数组
本质是数组,每个元素都是结构体
结构体指针变量
本质是变量,这个变量保存的是结构体变量的地址
void test02() {
Student lucy = {100,"lucy"};
Student *p;
p = &lucy;
cout<<(*p).age << " " << (*p).name << endl;
// 通过指针变量 使用->访问成员
cout<<p->age<<" "<<p->name<<endl;
// 还可以使用地址访问
cout<< (&lucy)->age << " " << (&lucy)->name << endl;
}
int main(int argc,char *argv[])
{
test02();
return 0;
}
080 结构体的深拷贝和浅拷贝
lucy.name保存的是“hello world”的首元素地址,但是这个字符串本身存储在文字常量区
#include <iostream>
#include<string.h>
using namespace std;
// 结构体指针成员
struct Student {
int age;
char *name;
};
void test01() {
Student lucy;
lucy.age = 18;
lucy.name = new char[32];
strcpy(lucy.name,"lucy");
cout<<lucy.age<< " " << lucy.name<<endl;
}
int main(int argc,char *argv[])
{
test01();
return 0;
}
两个指针成员都指向同一个堆区地址,delete会导致同一个空间多次释放
#include <iostream>
#include<string.h>
using namespace std;
// 结构体指针成员
struct Student {
int age;
char *name;
};
void test01() {
Student lucy;
lucy.age = 18;
lucy.name = new char[32];
strcpy(lucy.name,"lucy");
cout<<lucy.age<< " " << lucy.name<<endl;
//深拷贝
Student bob;
bob.age = lucy.age;
bob.name = new char[32];
strcpy(bob.name,lucy.name);
cout<<bob.age<< " " << bob.name<<endl;
}
int main(int argc,char *argv[])
{
test01();
return 0;
}
081 结构体对齐规则和位域
082 共用体
// 共用体
union Data{
char a;
short b;
int c;
};
void test02() {
Data ob;
ob.a = 10;
ob.b = 20;
ob.c = 30;
cout<<ob.a + ob.b + ob.c << endl;
}
int main(int argc,char *argv[])
{
test02();
return 0;
}
088 命名空间
089 结构体增强
先找局部变量,没有再去命名空间找
090 引用
void test03() {
int a = 10;
// 引用初始化 &修饰变量为引用 系统不会为引用开辟空间 a和b代表同一空间
int &b = a;
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"&a="<<&a<<endl;
cout<<"&b="<<&b<<endl;
b = 100;
cout<<"a="<<a<<" "<<"b="<<b<<endl;
}
int main(int argc,char *argv[])
{
test03();
return 0;
}