[問題] 繼承時的函數呼叫
請問為什麼下列程式碼的cout會是
Employee's Sal
Employee's Tax
Staff's bonus
Staff's Tax
3700
為什麼會先呼叫Employeee::Tax (Staff本身不是也有Tax?)
最後又會呼叫Staff::bonus和Staff::Tax ? (Tax用employee的,bonus用Staff的?)
開發平台:g++ , Linux
程式碼
#include <iostream>
using namespace std;
class Employee {
public:
Employee(int s) { salary = s; }
virtual int Sal() { cout << "Employee's Sal\n";
return salary - Tax() + bonus(); }
int Tax() { cout << "Employee's Tax\n";
return int(salary * 0.2); }
virtual int bonus() { cout << "Employee's bonus\n";
return 0; }
protected:
int salary;
};
class Staff : public Employee {
public:
Staff(int salary) : Employee(salary + 1000) {}
virtual int Tax() { cout << "Staff's Tax\n";
return int(salary * 0.1); }
int bonus() { cout << "Staff's bonus\n";
return Tax()+100; }
};
int main() {
Staff s(3000);
cout << s.Sal() << endl;
return 0;
}
※ 編輯: feathersss 來自: 203.67.223.239 (02/20 10:18)
→
02/20 10:28, , 1F
02/20 10:28, 1F
→
02/20 10:35, , 2F
02/20 10:35, 2F
推
02/20 13:48, , 3F
02/20 13:48, 3F
→
02/20 13:48, , 4F
02/20 13:48, 4F
→
02/20 13:51, , 5F
02/20 13:51, 5F
→
02/20 13:52, , 6F
02/20 13:52, 6F
→
02/20 13:53, , 7F
02/20 13:53, 7F
→
02/20 22:23, , 8F
02/20 22:23, 8F
→
02/20 22:23, , 9F
02/20 22:23, 9F
推
02/21 00:10, , 10F
02/21 00:10, 10F
→
02/21 07:42, , 11F
02/21 07:42, 11F
→
02/21 07:42, , 12F
02/21 07:42, 12F
推
02/21 12:20, , 13F
02/21 12:20, 13F
推
02/21 19:29, , 14F
02/21 19:29, 14F
→
02/21 20:45, , 15F
02/21 20:45, 15F
※ 編輯: feathersss 來自: 203.70.101.163 (02/21 20:51)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章