所以我有以下三个课程:
人员类:
#ifndef INC_7__LABOR_PERSON_H
#define INC_7__LABOR_PERSON_H
#include <string>
#include <iostream>
using namespace std;
class Person{
protected:
string lastName;
string firstName;
int dateOfBirth;
public:
Person(const string &lastName, const string &firstName, int dateOfBirth);
virtual void print(ostream& os = cout) const; //a virtualtol polimorfikus lehet.
};
ostream& operator <<(ostream& os, const Person&);
#endif //INC_7__LABOR_PERSON_H
Person 的构造函数:
Person::Person(const string &lastName, const string &firstName, int dateOfBirth) : lastName(lastName),
firstName(firstName),
dateOfBirth(dateOfBirth) {}
员工类:
#ifndef INC_7__LABOR_EMPLOYEE_H
#define INC_7__LABOR_EMPLOYEE_H
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
class Employee : public Person{
protected:
string position;
static int counter;
int id;
public:
Employee(const string &lastName, const string &firstName, int dateOfBirth, const string &position);
Employee(const string &lastName, const string &firstName, int dateOfBirth, int id);
virtual void print(ostream& os = cout) const;
int getId() const;
};
#endif //INC_7__LABOR_EMPLOYEE_H
Employee 的构造函数:
Employee::Employee(const string &lastName, const string &firstName, int dateOfBirth, const string &position)
: Person(lastName, firstName, dateOfBirth), position(position), id(counter++){}
经理类:
#ifndef INC_7__LABOR_MANAGER_H
#define INC_7__LABOR_MANAGER_H
#include "Employee.h"
#include <vector>
using namespace std;
class Manager : public Employee{
private:
vector<Employee*> employees;
public:
Manager(const string &lastName, const string &firstName, int dateOfBirth, const string &position);
static string MANAGER_POSITION;
virtual void print(ostream& os = cout) const;
void addEmployee(Employee*);
void deleteEmployee(int);
};
#endif //INC_7__LABOR_MANAGER_H
Manager 的构造函数:
string Manager::MANAGER_POSITION="manager";
Manager::Manager(const string &lastName, const string &firstName, int dateOfBirth, const string &position)
: Employee(lastName, firstName, dateOfBirth, position) {}
现在我的问题是我无法通过管理器访问 id 变量:
void Manager::deleteEmployee(int id)
{
for(int i = 0; i < employees.size(); ++i)
{
if(employees.at(i)->id == id) //HERE the "employees.at(i)->id" is the problem.
{
employees.erase(employees.begin() + i);
}
}
}
尽管 id 变量受到保护,但程序无法访问它。我通过使用 getter getId() 解决了这个问题,但我想知道为什么没有 getter 就无法访问它。
该程序是用 cygwin 编译器用 c++14 编写的。