【发布时间】: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;
因为老板->人数
我不知道为什么会发生这种情况,并且在我读到它的所有地方都说它应该编译得很好,但它没有。
谁能帮忙?
谢谢~
【问题讨论】:
-
Keeper 如何从 Employee 派生?向我们展示。
-
添加 keeper.h 供您查看它是如何派生的
标签: c++