簡體   English   中英

C++ 中的繼承和類

[英]Inheritance & Classes in C++

我不明白這個

class Employee { 
       public:   
          Employee(string name, float payRate); 
          string getName();   
          float getPayRate(); 
          float pay(float hoursWorked); 
       protected:   
          string name;   
          float payRate; 
}; 
class Manager : public Employee { 
       public:   
          Manager(string theName, float thePayRate, bool isSalaried); 
          bool getSalaried() const; 
          float pay(float hoursWorked) const; 
       private:   
          bool salaried; 
};

假設 pay() 方法已在 Employee 中聲明為虛擬方法。 並且,我們向 Employee 類添加一個 printPay() 方法:

void Employee::printPay(float hoursWorked) const 
{  
    cout << "Pay: " << pay(hoursWorked) << endl; 
} 

它在 Manager 中被繼承而不會被覆蓋。

當 mgr 對象調用 printPay() 時,管理器的 printPay() 中將調用哪個版本的 pay()。 解釋你的答案。

Manager mgr; 
mgr.printPay(40.0);

這是提供的答案:

即使在 Employee 中定義了 printPay(),也會在 printPay() 內部調用 pay() 的 Manager 版本! 為什么? 請記住:

void Employee::printPay(float hoursWorked) const 
{   
    ... pay(hoursWorked) ... 
} 

真的是簡寫:

void Employee::printPay(float hoursWorked) const 
{   
    ... this->pay(hoursWorked) ... 
} 

那有什么意思? 為什么不是答案多態性。

問題是您的printPay函數中的this類型不是Employee ,而是const Employee 所以你的函數Employee::pay(hoursWorked)不匹配。

在 clang++ 中,發出以下錯誤:

28 : <source>:28:24: error: member function 'pay' not viable: 'this' 
argument has type 'const Employee', but function is not marked const
cout << "Pay: " << pay(hoursWorked) << endl; 
                   ^~~
11 : <source>:11:17: note: 'pay' declared here
      float pay(float hoursWorked);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM