tips : 多数内容参考书中资料
一.函数间传值
2.数组在函数间的传递
1) 一维数组作为函数参数
eg: 数组是一个以int a[M]定义的一维int型数组,调用函数为fun(a)
- fun(int *parr)
- fun(int a[])
- fun(int a[M])
2) 二维数组作为函数参数
eg:数组是一个以int a[M][N]定义的二维数组,调用函数为fun(a)
- fun(int (*pa)[N] )
- fun(int a[][N] )
- fun(int a[M][N] )
tips: 仅传递数组名,即地址,此后形参,实参公用数组空间。
二.深拷贝与浅拷贝
1.默认复制构造函数
默认复制构造函数只是将数据成员的值进行赋值,如果构造函数中有分配指针内存的函数,但由于复制的仅仅是数据成员,并没有调用构造函数,
复制的是指针,则两者指向同一分配的空间,并没有为后者的分配空间。若前者的指针所指空间被清除,则后者的指针所指空间也被删除了。
但是销毁对象时,析构函数执行两次,也就是指针所指内存空间被释放两次,所以导致错误出现。
解决方法 1 : 析构函数增加一个判断是否为野指针的if判断语句
解决方法2 : 采用深拷贝,即拷贝构造函数
2. 浅拷贝的缺点
阅读课本例子,分析出现问题
#include<iostream>
#include<string.h>
using namespace std;
class Student
{private:
int no;
char *name;
int score;
public:
Student(int n,const char *na,int s)
{ no = n;
name = new char(strlen(na)+1);
strcpy(name,na);
score = s;
}
~Student()
{ //cout<<"detecting"<<endl;
delete []name;
cout<<"destorying"<<endl;
}
friend void display(Student &stu);
friend void change(Student &stu);
};
void display(Student &stu)
{ cout<<stu.name<<endl;
}
void change(Student &stu)
{ cin>>stu.name;
}
int main()
{ Student stu1(1,"new_class",89),stu2(stu1);
cout<<" Student stu1(1,new_class,89),stu2(stu1); "<<endl;
display(stu1);
cout<<"改变stu1的名字:";
change(stu1);
cout<<"输出stu2的名字:";
display(stu2);
cout<<"可见stu1和stu2所指为同一内存空间\n"<<endl;
cout<<"程序执行完毕,开始销毁对象"<<endl;
return 0;
}
stu2是stu1的浅拷贝,当stu1中name所指的字符数组值被改变时,stu2的同时也被改变。
若想改变stu1而不改变stu2中的name,则需要给stu2的那么name开辟一个指向的内存空间,即深拷贝
3.深拷贝
#include<iostream>
#include<string.h>
using namespace std;
class Student
{private:
int no;
char *name;
int score;
public:
Student(int n,const char *na,int s)
{ no = n;
name = new char(strlen(na)+1);
strcpy(name,na);
score = s;
}
Student(const Student& stu):no(stu.no),score(stu.score) //const 相当于把 常量 值传过来
{ name = new char(strlen(stu.name)+1);
strcpy(name,stu.name);
}
~Student()
{ //cout<<"detecting"<<endl;
if(name != NULL){
delete []name;
cout<<"destorying"<<endl;
}
}
friend void display(Student &stu);
friend void change(Student &stu);
};
void display(Student &stu)
{ cout<<stu.name<<endl;
}
void change(Student &stu)
{ cin>>stu.name;
}
int main()
{ Student stu1(1,"new_class",89),stu2(stu1);
cout<<" Student stu1(1,new_class,89),stu2(stu1); "<<endl;
display(stu1);
cout<<"改变stu1的名字:";
change(stu1);
cout<<"输出stu2的名字:";
display(stu2);
cout<<"若destorying出现两次,则可见stu1和stu2所指不为同一内存空间\n"<<endl;
cout<<"程序执行完毕,开始销毁对象"<<endl;
return 0;
}
name所指内存被释放两次,可见两个对象所指内存空间不同