1.动态内存
//new一个数据
int *a = new int(2020);
delete a;
//new长度为5的数组,使用默认构造函数
int *a = new int[5];
delete [] a;
//new一个二维数组
int (*a)[5] = new t[5][5];
delete [] a;
2.引用
1.引用不分配空间(高效率),必须初始化
2.可以引用指针变量
3.引用的对象必须存在,不能是数组,不能是void
4.const int &a可以防止引用改变a的值
5.当函数参数(实参也能被改变)/返回值时不会产生副本,
void fun(int &a) {
a *= 2;
}
int main()
{
int a=2;
int& b = a;
int* c = new int(520);
int*& d = c;
cout << a << endl;
b *= 2; //改变a的值
cout << a<<endl;
fun(a);
cout << a << endl;
cout << "内存->" << c << "值->" << *c << endl;
*d = 1314; //改变c指向的内容的值
cout << "内存->" << c << "值->" << *c << endl;
d = &a; //改变c指向哪里
cout << "内存->" << c << "值->" << *c << endl;
return 0;
}
结果
3.函数默认参数
void fun(int a, int b, int c=200, int d=404);//在声明时设置默认值
int main()
{
fun(1, 2, 3, 4); //完整
fun(11, 22, 33); //省略d
fun(11, 22); //省略cd
return 0;
}
void fun(int a, int b, int c, int d) {
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << endl;
}
结果
4.重载函数
void fun(int a) {
cout << "参数为整数"<<endl;
}
void fun(const char *a) {
cout << "参数为字符串" << endl;
}void fun(int a,char b) {
cout << "两个参数" << endl;
}
int main()
{
fun(1);
fun("gg");
fun(1,'2');
return 0;
}
结果
5.深拷贝/浅拷贝
在拷贝时,指针对象是选择直接复制指针(浅拷贝),还是复制指针指向的堆(深拷贝)
class phone {
public:
int *id;
int ram;
phone():id(NULL),ram(-1) { }
phone(int id,int ram) {
this->id = new int(id);
this->ram = ram;
}
~phone() {
delete id;
}
//浅拷贝,不复制堆的数据
void s_copy(const phone& t) {
id = t.id;
ram = t.ram;
}
//深拷贝,复制堆
void d_copy(const phone& t) {
id = new int(*t.id);
ram = t.ram;
}
};
int main()
{
phone a(1001,8);
phone b, c;
b.s_copy(a);//采用浅拷贝
c.d_copy(a);//采用深拷贝
*a.id = -1;
a.ram = 16;//改变a的值
cout << *a.id << " " << a.ram << endl; //-1 16
cout << *b.id << " " << b.ram << endl; //-1 8
cout << *c.id << " " << c.ram << endl; //1001 8
//c的id和a的id指向同一块内存,所以析构函数必出错
getchar();
return 0;
}
6.静态成员变量/函数
静态成员变量类似全局变量,所以不计入类的内存,一般也不能在类中初始化
class phone {
public:
static int num;//声明静态成员变量
phone(){ }
void print() {
cout<<num<<endl;
}
void setNum(int n) {
num = n;
}
};
int phone::num = 5;//必须在使用前初始化
int main()
{
phone a,b;
a.print(); //5
b.print(); //5
b.setNum(200);
a.print(); //200
phone::num = phone::num*10;
a.print(); //2000
return 0;
}
静态成员函数,不能访问类中的非静态变量,无法声明const
class phone {
public:
static int num;
int id;
phone(int _id):id(_id){
}
static void print() {
//cout<<id<<endl; 不可以访问非静态成员变量
cout<<num<<endl;
}
};
int phone::num = 5;
int main()
{
phone a(1001);
a.print(); //对象.函数
phone::print(); //类.函数
return 0;
}