【问题标题】:const int Employee::number is protectedconst int Employee::number 受保护
【发布时间】:2017-01-09 21:15:56
【问题描述】:

一个奇怪的问题;我在处理一些我遇到的问题时遇到了问题,我不知道为什么会发生这种情况。

所以我有 2 个文件(实际上更多,但那些并不重要),分别称为 Employee 和 Keeper。 Employee 是基类,Keeper 是派生类。

员工有几个属性和一个名为 saveFile 的方法,而 keep 继承了这些。

员工.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->number 时,我从 employee.h 中得到了 const int number 的错误。

错误在这一行:

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

因为老板->人数

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

谁能帮忙?

谢谢~

【问题讨论】:

标签: c++


【解决方案1】:

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

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

【讨论】:

  • 我必须使用继承
猜你喜欢
  • 2010-11-02
  • 2016-02-19
  • 1970-01-01
  • 2014-03-05
  • 2015-09-05
  • 1970-01-01
  • 2020-03-31
  • 2016-08-22
  • 2011-06-06
相关资源
最近更新 更多