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 };
第二种相对而言更简便,但往往浪费内存,不确定传入的字符串参数大小。