復制構造函數是一種特殊的構造函數,有一般構造函數的特性。它的功能是用一個已知的對象來初始化一個被創建的同類對象。復制構造函數的參數傳遞方式必須按引用來進行傳遞,請看實例:
#include <iostream>#include <cstring>using namespace std ; class Student { private : char name[8]; int age ; char sex ; int score ; public : void disp(); //打印信息的函數聲明 Student(char name[],int age , char sex ,int score); //構造函數聲明 Student(Student &dx); //復制構造函數的聲明 ~Student(); //析構函數的聲明};//打印信息函數的實現void Student::disp(){ cout << this->name << endl ; cout << this->age << endl ; cout << this->sex << endl ; cout << this->score << endl ;}//構造函數的實現 Student::Student(char name[],int age , char sex ,int score){ strcpy(this->name,name); this->age = age ; this->sex = sex ; this->score = score ;}//復制構造函數的實現Student::Student(Student &dx){ strcpy(this->name , dx.name); this->age = dx.age ; this->sex = dx.sex ; this->score = dx.score ;} //析構函數的實現Student::~Student(){ cout << "程序結束" << endl ;} int main(void){ Student stu1("YYX",23,'N',86); Student stu2(stu1); stu1.disp() ; stu2.disp() ; return 0 ;}
運行結果:
YYX
23
N
86
YYX
23
N
86
程序結束
程序結束
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答