2017-01-09 101 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