[問題] this 加不加的差別
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Dev-C++
程式碼(Code):(請善用置底文網頁, 記得排版)
我自己寫的:
#include <cstdlib>
#include <iostream>
#include <iostream.h>
class Employee{
char Name[20];
int BaseSalary;
int OvertimePay;
public:
Employee(char name[],int bs,int op){
strcpy(name,Name);
bs=BaseSalary;
op=OvertimePay;
}
int TotalPay(){return BaseSalary+OvertimePay;}
};
class Manager:public Employee{
int DutyAllowance;
public:
Manager(char name[],int bs,int op,int da):Employee(name,bs,op){
da=DutyAllowance;
}
int TotalPay(){return Employee::TotalPay()+DutyAllowance;}
};
int main(){
Employee rd("john",10000,50000);
Manager lead("fdfs",4333,556324,555453);
cout<<rd.TotalPay()<<endl;
cout<<lead.TotalPay()<<endl;
system("pause");
return 0;
}
書上寫之方式:
#include <cstdlib>
#include <iostream>
#include <iostream.h>
class Employee{
char Name[20];
int BaseSalary;
int OvertimePay;
public:
/* Employee(char Name[],int BaseSalary,int OvertimePay){
strcpy(this->Name,Name);
this->BaseSalary=BaseSalary;
this->OvertimePay=OvertimePay;
}
*/
int TotalPay(){return BaseSalary+OvertimePay;}
};
class Manager:public Employee{
int DutyAllowance;
public:
/* Manager(char Name[],int BaseSalary,int OvertimePay,int DutyAllowance):Employee(Name,BaseSalary,OvertimePay){
this->DutyAllowance=DutyAllowance;
*/ }
int TotalPay(){return Employee::TotalPay()+DutyAllowance;}
};
int main(){
Employee rd("john",10000,50000);
Manager lead("fdfs",4333,556324,555453);
cout<<rd.TotalPay()<<endl;
cout<<lead.TotalPay()<<endl;
system("pause");
return 0;
}
補充說明(Supplement):
小弟我之前在練習題目時,發現有this方面的問題
爬文之後很多人都說this表示"自己"之意思
所以想說書上這樣寫應該是要辨別萬一在相同名稱時
可以辨認出誰是誰....但是我不用this的方法寫
編譯會過,但卻會出現程式錯誤
我的問題是:
1."this是不是用在相同名稱可以分辨"這樣的觀念是對還是錯??
2.為什麼書上的可以執行...小弟寫的問題出在哪裡??
請各位高手替我解答
(不一樣的地方已用/**/框起來了,其餘皆相同)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.175.18.6
※ 編輯: grandoph 來自: 1.175.18.6 (05/09 21:55)
→
05/09 21:56, , 1F
05/09 21:56, 1F
※ 編輯: grandoph 來自: 1.175.18.6 (05/09 21:58)
→
05/09 21:59, , 2F
05/09 21:59, 2F
→
05/10 00:59, , 3F
05/10 00:59, 3F
→
05/10 01:01, , 4F
05/10 01:01, 4F
→
05/10 07:46, , 5F
05/10 07:46, 5F