const int Employee :: number受保护

时间:2017-01-09 21:15:57

标签: c++

有点奇怪的概率;当我遇到一些我遇到困难的事情时,我遇到了这些事情,我不知道为什么会这样。

所以我有2个文件(实际上更多,但那些不重要)叫做Employee和Keeper。 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 ...
};

现在,当我在saveFile方法中调用boss-&gt;数字时,我从employee.h得到了const int数的错误。

错误在这一行:

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

因为boss-&gt;数字

我不知道为什么会发生这种情况,而且在我读到的任何地方都说它应该编译得很好,但它没有。

有人可以帮忙吗?

谢谢〜

1 个答案:

答案 0 :(得分:1)

number对象的boss成员受到对象本身外部函数的直接访问保护,即使属于同一类型的对象。例外是友元类和方法,以及复制构造。

回应评论:继承不是你的问题。对象本身中的数据受到保护,不受外部访问。您的Keeper对象继承了它可以访问的自己的number成员,以及指向boss Employee的指针。要解决您的问题,您可以将number设为公开,也可以添加访问方法以返回值。