先說(shuō)C++中的類铲觉,和結(jié)構(gòu)體的區(qū)別
比如說(shuō),結(jié)構(gòu)體中吓坚,是不能定義方法的撵幽,只能定義指針函數(shù)
在類中,是可以定義方法的礁击,且類中盐杂,可以有this,直接指向變身的變量,這個(gè)在結(jié)構(gòu)體中哆窿,都是不存在的链烈。
構(gòu)造函數(shù)
class Teacher{
? ?private:
? ?char *name;
? ?int age;
? ?public:
//無(wú)參構(gòu)造函數(shù)(寫了,就會(huì)覆蓋默認(rèn)的無(wú)參構(gòu)造函數(shù))
? ?Teacher(){
? ? ? ?cout << "無(wú)參構(gòu)造函數(shù)" << endl;
}
//有參構(gòu)造函數(shù)會(huì)覆蓋默認(rèn)的構(gòu)造函數(shù)
? ?Teacher(char *name, int age){
? ? ?this->name = name;
? ? ?this->age = age;
? ? cout << "有參構(gòu)造函數(shù)" << endl;
? }
};
void main(){
?Teacher t1;
?Teacher t2("yuehan",20);
//另外一種調(diào)用方式
? Teacher t3 = Teacher("jack",21);
? system("pause");
}
最后打印出的就是挚躯,無(wú)參强衡,有參,有參
很簡(jiǎn)單码荔,跟JAVA其實(shí)差不多
析構(gòu)函數(shù)就是作善后處理的函數(shù)食侮,如下
class Teacher{
? ?private:
? ?char *name;
? ?int age;
? ?public:
? ?//無(wú)參構(gòu)造函數(shù)賦默認(rèn)值
? ?Teacher(){
? ? ? this->name = (char*)malloc(100);
? ? ? strcpy(name,"jack walson");
? ? ? age = 20;
? ? ? cout << "無(wú)參構(gòu)造函數(shù)" << endl;
}
//析構(gòu)函數(shù)
//當(dāng)對(duì)象要被系統(tǒng)釋放時(shí),析構(gòu)函數(shù)被調(diào)用
//作用:善后處理
~Teacher(){
? ?cout << "析構(gòu)" << endl;
? ?//釋放內(nèi)存
? ?free(this->name);
? ?}
};
void func(){
? ?Teacher t1;
}
void main(){
? ?func();
? ?system("pause");
? ?}
這樣目胡,當(dāng)對(duì)象被系統(tǒng)釋放時(shí),析構(gòu)函數(shù)也會(huì)被調(diào)用
下面講講拷貝
先看一個(gè)例子:
class Teacher {
? ?public:
? ?char *name;
? ?int age;
? ?public:
? ?Teacher(char *name, int age) {
? ? ? ?this->name = name;
? ? ? ?this->age = age;
? ? ? cout << "有參構(gòu)造函數(shù)" << 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打印出來(lái)都是一直的,都是會(huì)yan域蜗。而在此處巨双,只有t1是yan噪猾,t2的打印,依然會(huì)是rose筑累。所以可以看出袱蜡,這里的拷貝,是值拷貝慢宗,而不是指向指針坪蚁。其效果等同于下面的寫法:
class Teacher {
public:
char *name;
int age;
public:
Teacher(char *name, int age) {
? ?this->name = name;
? ?this->age = age;
? ?cout << "有參構(gòu)造函數(shù)" << endl;
}
//拷貝構(gòu)造函數(shù)(值拷貝)
//默認(rèn)拷貝構(gòu)造函數(shù),就是值拷貝
Teacher(const Teacher &obj) {
? ?this->name = obj.name;
? ?this->age = obj.age;
? ?cout << "拷貝構(gòu)造函數(shù)" << endl;
}
void myprint() {
? ?cout << name << "," << age << endl;
}
};
可以看出镜沽,這里面就重寫了拷貝構(gòu)造函數(shù)敏晤,其效果,和不寫是一樣的缅茉。原因前面說(shuō)了嘴脾,這是默認(rèn)就是值拷貝,這里的寫法蔬墩,也是值拷貝译打。