2017-03-21 61 views
1

因此,我的程序的全部要點是從文件中讀取輸入並進行一些計算,然後將結果輸出到文件中。 有幾個文件涉及到這一點,但爲了簡單起見,我將只包含我的程序的兩個實現文件。實現文件「employee」是基類,文件「merit」是派生類。使用繼承時沒有得到文件的正確輸出

現在的輸出,我應該得到它的格式爲:ID ---工資

我得到正確的結果的薪水,但我得到了錯誤的號碼ID。我知道這與在merit :: print()函數中的事實有關,它打印[merit :: ID]而不是[employee :: ID]。

有沒有辦法讓我打印出員工::身份證,而不是身份證::身份證?

以下是基礎類文件(員工檔案):

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include "employee.h" 
#include "merit.h" 


using namespace std; 

// The definition of the members functions of the class employee goes here. 

void employee::readData(ifstream& inf) 
{ 
    inf >> ID >> Job_class >> Years >> Ed; 
} 




void employee::print(ofstream& outf) const 
{ 
    outf << ID << setw(15) << fixed << showpoint << setprecision(2) << "$ " << sal << endl; 
} 

下列文件派生類文件(文件優點):

void merit::readData(ifstream& inf) 
{ 
    employee::readData(inf); 
    inf >> mer; 

} 



void merit::print(ofstream& outf) const 
{ 
    outf << ID << setw(15) << fixed << showpoint << setprecision(2) << "$ " << salary << endl; 
} 
+0

「ID」是靜態的嗎? – Jerfov2

+0

@ Jerfov2 ID是從輸入文件中讀取的。然後它應該顯示在輸入文件中。函數merit :: readData()調用函數employee :: readData(),它從輸入文件讀取ID。 – AJ05

+0

@ Jerfov2 ID是私密的。它是在員工頭文件中聲明的。 – AJ05

回答

0

你還沒有告訴我們您的頭文件定義了類,所以這可能不太對。我假設employeemerit都有一個名爲ID的成員。

要訪問與派生類中的成員具有相同名稱的基類成員,只需限定該名稱。在你的情況下,使用employee::ID而不是ID

您已在評論中指出IDemployee中是私人的,因此您需要使用getter函數。添加類似int getEmployeeID() const;到您的employee類(它可以是保護或公共),將返回該ID。然後從您merit類中調用以獲取員工ID。

+0

謝謝你,這是非常有益的。 – AJ05