1.构造函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <iostream>
#include <stdarg.h>
using namespace std;
class Teacher {
private :
char *name;
int age;
public :
//无参构造函数
Teacher() {
cout << "无参构造函数" << endl;
}
//有参构造函数会覆盖默认的无参构造函数
Teacher(char *name, int age) {
this->name = name;
this->age = age;
cout << "有参构造函数" << endl;
}
};
void main() {
Teacher t1;
Teacher t2("xiaoming",11);
//另外一种调用方式
Teacher t3 = Teacher("jack",55);
getchar();
}
2.析构函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <iostream>
#include <stdarg.h>
using namespace std;
class Teacher
{
public:
//无参构造函数赋默认值
Teacher() {
this->name = (char*)malloc(100);
strcpy(name,"jack");
age = 21;
cout << "无参构造函数" << endl;
}
//析构函数
//当对象要被系统释放时,析构函数被调用
//作用:善后处理
~Teacher() {
cout << "析构" << endl;
//释放内存
free(this->name);
}
private:
char *name;
int age;
};
void func() {
Teacher t1;
}
void main() {
func();
getchar();
}
3.拷贝构造函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <iostream>
#include <stdarg.h>
using namespace std;
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 = name;
this->age = age;
cout << "拷贝构造函数" << endl;
}
void myprint() {
cout << name <<","<< age << endl;
}
};
Teacher func(Teacher t) {
t.myprint();
return t;
}
void main() {
Teacher t1("rose",22);
//拷贝构造函数被调用的场景
//1.声明时赋值
//Teacher t2 = t1;
//t2.myprint();
//2.作为参数传入,实参给形参赋值
//func(t1);
//3.作为函数返回值返回,给变量初始化赋值
//Teacher t3 = func(t1);
//这里不会被调用
//Teacher t1;
//Teacher t2;
//t1 = t2;
getchar();
}
浅拷贝
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();
getchar();
}
深拷贝
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("jack",21);
Teacher t2 = t1;
t2.myprint();
}
void main() {
func();
getchar();
}