1 構(gòu)造函數(shù)特點: 主要是在兩方面起作用: 1,構(gòu)造函數(shù) 在創(chuàng)建對象時 分配空間 2 構(gòu)造函數(shù) 在創(chuàng)建對象時 初始化 析構(gòu)函數(shù): 在撤銷函數(shù)時,收回占用的內(nèi)存 以及其他的清理工作 -------------------------------------------------------------------------------- 源代碼1: #include<iostream> using namespace std; class Point{ private: int x,y; public: int Init(int x,int y){ this->x=x; this->y=y; } int show(){ cout<<x<<","<<y<<endl; } }; int main(){ Point p; p.Init(1,2); p.show(); } 結(jié)果: ![]() 編輯代碼遇到的bug; //類名沒寫全 //類名后面() -------------------------------------------------------------------------------- 2 ![]() 源代碼2: #include<iostream> #include<cstring> using namespace std; class Person{ private: char name[12]; int age; char sex[4]; public : Person(const char*n,int a,const char*s){//構(gòu)造函數(shù) strcpy(name,n); age=a; strcpy(sex,s); } int Show(){ cout<<"name:"<<name<<",age:"<<age<<",sex:"<<sex<<endl; } }; int main(){ Person p("zhao",12,"nan"); p.Show(); } 3//構(gòu)造函數(shù)主要是 無參構(gòu)造函數(shù) 有參構(gòu)造函數(shù) 拷貝構(gòu)造函數(shù) #include<iostream> #include<cstdlib> #include<cstring> using namespace std; class Test{ private: int a; char* p; public: Test(); ~Test(); void print(){ cout<<a<<endl; cout<<p<<endl; } }; Test::Test(){ a=10; p=(char*)malloc(sizeof(100)); strcpy(p,"Rita"); cout<<"我是構(gòu)造函數(shù)"<<endl; } Test::~Test(){ if(p!=0){ free(p); } cout<<"我是析構(gòu)函數(shù),我被調(diào)用調(diào)用了!"<<endl; } void objplay(){ Test t1; Test t2; t1.print(); cout<<endl<<endl; t2.print(); } int main(){ objplay(); system("pause"); return 0; } ![]() 構(gòu)造函數(shù)初始化列表: ![]() ![]() 1 Point::Point(int x1,int y1){x=x1;y=y1;} 2 Point::Point(int x1,int y2):x(x1),y(y1){} 3 Point::Point(int x1,int y1,const char*p1){x=x1;y=y1;strcpy(p,p1);} 4 Point::Point(int x1,int y1,const char*p1):x(x1),y(y1){ strcpy(p,p1); } 4 ![]() 分享知識,分享快樂!希望中國站在編程之巔! ----融水公子 |
|