先说C++中的类,和结构体的区别
比如说,结构体中,是不能定义方法的,只能定义指针函数
在类中,是可以定义方法的,且类中,可以有this,直接指向变身的变量,这个在结构体中,都是不存在的。
构造函数
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("yuehan",20);
//另外一种调用方式
Teacher t3 = Teacher("jack",21);
system("pause");
}
最后打印出的就是,无参,有参,有参
很简单,跟JAVA其实差不多
析构函数就是作善后处理的函数,如下
class Teacher{
private:
char *name;
int age;
public:
//无参构造函数赋默认值
Teacher(){
this->name = (char*)malloc(100);
strcpy(name,"jack walson");
age = 20;
cout << "无参构造函数" << endl;
}
//析构函数
//当对象要被系统释放时,析构函数被调用
//作用:善后处理
~Teacher(){
cout << "析构" << endl;
//释放内存
free(this->name);
}
};
void func(){
Teacher t1;
}
void main(){
func();
system("pause");
}
这样,当对象被系统释放时,析构函数也会被调用
下面讲讲拷贝
先看一个例子:
class Teacher {
public:
char *name;
int age;
public:
Teacher(char *name, int age) {
this->name = name;
this->age = age;
cout << "有参构造函数" << endl;
}
void myprint() {
cout << name << "," << age << endl;
}
};
void main() {
Teacher t1("rose", 20);
Teacher t2 = t1;
t1.name = "yan";
t1.myprint();
t2.myprint();
system("pause");
}
如上直接赋值,在JAVA中,t1,t2打印出来都是一直的,都是会yan。而在此处,只有t1是yan,t2的打印,依然会是rose。所以可以看出,这里的拷贝,是值拷贝,而不是指向指针。其效果等同于下面的写法:
class Teacher {
public:
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;
}
};
可以看出,这里面就重写了拷贝构造函数,其效果,和不写是一样的。原因前面说了,这是默认就是值拷贝,这里的写法,也是值拷贝。