C++兩種字符串傳參構造函數


第一種:

 1 #include"iostream"
 2 #include"string"
 3 using namespace std;
 4 
 5 class Motor{
 6 protected:
 7     int n;
 8     int tire;
 9     double motor;
10     char *str1;    //基類為指針
11     char *str2;
12 public:
13     virtual void Display()=0;
14 };
15 
16 class Car:public Motor{
17 public:
18     Car(char *Str1,char *Str2,int N,int Tire,double Motor){
19         str1 = new char[strlen(Str1)+1];    //要先獲得字符串大小
20         str2 = new char[strlen(Str2)+1];
21         strcpy(str1,Str1);
22         strcpy(str2,Str2);
23         n = N;
24         tire = Tire;

25         motor = Motor;
26     }
27     ~Car(){
28         delete[] str1;    //最后要刪除內存
29         delete[] str2;
30     };
31     virtual void Display(){
32         cout<<"the car"<<"可載人數:"<<n<<"、輪胎數:"<<tire<<"、馬力數:"<<motor<<endl;
33         cout<<"產於"<<str1<<"車的主人為:"<<str2<<endl;
34     }
35 };

第一種相對而言可以節省內存,不怕傳入的字符串過長,但要記得刪除指針釋放內存

第二種:

 1 #include"iostream"
 2 using namespace std;
 3 #define pi 3.14159
 4 
 5 class Motor{
 6 protected:
 7     int man,wheel,mata;
 8     char produce[20];    //基類為數組
 9     char owner[20];
10 public:
11     Motor(int m,int w,int ma,char* pro,char* own){
12         man=m; wheel=w; mata=ma;
13         strcpy(produce,pro);    //不必獲得字符串大小,因開始已指定
14         strcpy(owner,own);
15     }
16     //無需虛構函數去刪除指針,不會泄露內存
17     virtual void Dispaly(){
18         cout<<"the motor"<<"可載人數:"<<man<<"、輪胎數:"<<wheel<<"、馬力數:"<<mata<<endl;
19         cout<<"產於"<<produce<<"車的主人為:"<<owner<<endl;
20     }
21 };
22 
23 class Car:public Motor{
24 public:
25     Car(int m,int w,int ma,char* pro,char* own):Motor(m, w, ma, pro, own){}
26     void Dispaly(){
27         cout<<"the car"<<"可載人數:"<<man<<"、輪胎數:"<<wheel<<"、馬力數:"<<mata<<endl;
28         cout<<"產於"<<produce<<"車的主人為:"<<owner<<endl;
29     }
30 };


第二種相對而言更簡便,但往往浪費內存,不確定傳入的字符串參數大小。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM