1.可变参数
void func(int i,...)
{
//可变参数指针
va_list args_p;
//开始读取可变参数,i是最后一个固定参数
va_start(args_p,i);
int a = va_arg(args_p,int);
char b = va_arg(args_p, char);
int c = va_arg(args_p, int);
cout << a << endl;
cout << b << endl;
cout << c << endl;
//结束
va_end(args_p);
}
void main(){
func(9,20,'b',30);
system("pause");
}
2.构造函数、析构函数、拷贝构造函数
构造函数
class Teacher{
private:
char *name;
int age;
public:
// 1 无参构造函数(写了,就会覆盖默认的无参构造函数)
Teacher(){
cout << "无参构造函数" << endl;
}
//2 无参构造函数赋默认值
Teacher(){
this->name = (char*)malloc(100);
strcpy(name,"jack walson");
age = 20;
cout << "无参构造函数" << endl;
}
//有参构造函数会覆盖默认的构造函数
Teacher(char *name, int age){
this->name = name;
this->age = age;
cout << "有参构造函数" << endl;
}
//析构函数
//当对象要被系统释放时,析构函数被调用
//作用:善后处理
~Teacher(){
cout << "析构" << endl;
//释放内存
free(this->name);
}
};
void main(){
// Teacher t1;
Teacher t2("yuehan",20);
//另外一种调用方式
Teacher t3 = Teacher("jack",21);
system("pause");
}
拷贝构造函数
class Teacher{
private:
char *name;
int age;
public:
Teacher(char *name, int age){
this->name = name;
this->age = age;
cout << "有参构造函数" << endl;
}
//拷贝构造函数(值拷贝)
//默认拷贝构造函数,就是值拷贝
Teacher(const Teacher &obj){
this->name = obj.name;
this->age = obj.age;
cout << "拷贝构造函数" << endl;
}
void myprint(){
cout << name << "," << age << endl;
}
};
Teacher func1(Teacher t){
t.myprint();
return t;
}
void main(){
Teacher t1("rose",20);
//拷贝构造函数被调用的场景
//1.声明时赋值
//Teacher t2 = t1;
//t2.myprint();
//2.作为参数传入,实参给形参赋值
func1(t1);
//3.作为函数返回值返回,给变量初始化赋值
//Teacher t3 = func1(t1);
//这里不会被调用
//Teacher t1 ;
//Teacher t2;
//t1 = t2;
system("pause");
}
//浅拷贝(值拷贝)问题
class Teacher{
private:
char *name;
int age;
public:
Teacher(char *name, int age){
this->name = (char*)malloc(100);
strcpy(this->name,name);
this->age = age;
cout << "有参构造函数" << endl;
}
~Teacher(){
cout << "析构" << endl;
//释放内存
free(this->name);
}
void myprint(){
cout << name << "," << age << endl;
}
};
void func(){
Teacher t1("rose", 20);
Teacher t2 = t1;
t2.myprint();
}
void main(){
func();
system("pause");
}
//深拷贝
class Teacher{
private:
char *name;
int age;
public:
Teacher(char *name, int age){
int len = strlen(name);
this->name = (char*)malloc(len+1);
strcpy(this->name, name);
this->age = age;
cout << "有参构造函数" << endl;
}
~Teacher(){
cout << "析构" << endl;
//释放内存
free(this->name);
}
//深拷贝
Teacher(const Teacher &obj){
//复制name属性
int len = strlen(obj.name);
this->name = (char*)malloc(len+1);
strcpy(this->name,obj.name);
this->age = obj.age;
}
void myprint(){
cout << name << "," << age << endl;
}
};
void func(){
Teacher t1("rose", 20);
Teacher t2 = t1;
t2.myprint();
}
void main(){
func();
system("pause");
}