2017-01-09 43 views
-2

有點奇怪的概率;當我遇到某些事情時,我遇到了,我不知道爲什麼會發生這種情況。const int Employee :: number受保護

因此,我有2個文件(實際上更多,但這些都非常重要)稱爲員工和守護者。 Employee是基類,Keeper是派生類。

員工有幾個屬性和一個名爲saveFile的方法,keep繼承這些屬性。

Employee.h:

protected: 

    const int   number; 
    const std::string name; 
    int     age; 

    // All ordinary employees 
    Employee   *boss = nullptr;   // works for ... 

public: 
    void saveFile(std::ostream&) const; 

Keeper.cc

void Keeper::saveFile(ostream& out) const 
{ 
    out << "3\t3\t" 
    << number << "\t" << name << "\t" << age 

    // The error happen here on boss->number 
    << "\t" << cage->getKind() << "\t" << boss->number << endl; 
} 

Keeper.h(完整的代碼)

#ifndef UNTITLED1_KEEPER_H 
#define UNTITLED1_KEEPER_H 

#include "Employee.h" 
// tell compiler Cage is a class 
class Cage; 
#include <string> // voor: std::string 
#include <vector> // voor: std::vector<T> 
#include <iostream> // voor: std::ostream 

class Keeper : public Employee { 
    friend std::ostream& operator<<(std::ostream&, const Keeper&); 

public: 
Keeper(int number, const std::string& name, int age); 

~Keeper(); 
/// Assign a cage to this animalkeeper 
void setCage(Cage*); 

/// Calculate the salary of this employee 
float getSalary() const; 

/// Print this employee to the ostream 
void print(std::ostream&) const; 

// ===================================== 
/// Save this employee to a file 
void saveFile(std::ostream&) const; 
protected: 

private: 
    // Keepers only 
    Cage *cage = nullptr;   // feeds animals in ... 
}; 

現在,我得到的const int的數錯誤employee.h當我調用saveFile方法中的boss->編號時。

的錯誤是在這條線:

<< "\t" << cage->getKind() << "\t" << boss->number << endl; 

因爲BOSS-的>數

我不知道爲什麼會這樣,到處我讀它說,它應該編譯得很好,但它不。

任何人都可以幫忙嗎?

謝謝〜

+2

http://stackoverflow.com/help/mcve – melpomene

+0

守護者如何從員工派生?給我們看一看。 – AndyG

+0

添加keeper.h爲你看看它是如何派生的 – Ellisan

回答

1

boss對象的number構件由函數對象本身之外,防止直接訪問,即使在同一類型的對象所擁有。例外是朋友類和方法,以及複製構造函數。

回覆評論:繼承不是你的問題。對象本身的數據受到外部訪問的保護。您的Keeper對象會繼承其可以訪問的其自己的number成員以及指向boss員工的指針。要解決您的問題,您可以使number公開,或添加訪問方法以返回值。

+0

我必須使用繼承 – Ellisan

+0

您的編輯答案爲我做了! – Ellisan