我正在为我的学校使用 C++ 开发一个项目
我有 2 个类别:雇员和教师。 Teacher 源自 Employe 并覆盖了他的功能。
我们重写运算符<<
打印员工或教师的一些信息。
每个类(class)都有一个const int attribute LevelAcces_
。
对于雇员,为5,对于教师为20。
当我在 main.cpp 中创建教师时,我调用教师的运算符 << 的重写来打印他的信息。 所以这个函数被称为:
ostream& operator<<(ostream& os, const Teacher& pTeacher){
os << (pTeacher);
return os;
}
但是,函数通过行 "os << (pTeacher);"
调用自身并执行导致堆栈溢出的循环。
我想要这条线 "os << (pTeacher)"
调用我类(class) Employe 的运算符(operator),而不是我类(class) Teacher 的运算符(operator)。
重写 Employe 中的运算符<<:
ostream& operator<<(ostream& os, const Employe& pEmploye){
os << "Name: " << pEmploye.name_ << endl;
os << "Class: " << pEmploye.getClass() << endl;
os << "LevelAcces: " << pEmploye.getLevelAccess() << endl;
return os;
}
我尝试将我的老师转换为 Employe,但当它打印消息时,LevelAcces 为 5(我想要 20,因为我的 Employe 是老师)。
我还尝试使用 Employe::operator<< 但operator<< 不是 Employe 的成员,所以它不起作用...
所以,这是我的问题:
如何在教师的运算符<<中使用 Employe 的运算符<<并打印正确的信息(LevelAccess = 20 而不是 5)?
我也想到了“虚拟”,但我们的教授告诉我们没有必要使用这个词。
提前致谢:)
这是更完整的代码:
main.cpp:
Teacher Garry("Garry");
cout << Garry << endl;
Employe.cpp:
#include "Employe.h"
using namespace std;
Employe::Employe(){
name_ = "";
}
Employe::Employe(string pName){
name_ = pName;
}
string Employe::getName() const{
return name_;
}
unsigned int Employe::getLevelAccess() const{
return levelAccess_;
}
string Employe::getClass() const{
return typeid(*this).name();
}
ostream& operator<<(ostream& os, const Employe& pEmploye){
os << "Name: " << pEmploye.name_ << endl;
os << "Class: " << pEmploye.getClass() << endl;
os << "LevelAcces: " << pEmploye.getLevelAccess() << endl;
return os;
}
在 Employe.h 中使用此内容:
private:
static const unsigned int LevelAccess_ = 5;
教师.cpp:
#include "teacher.h"
using namespace std;
Teacher::Teacher(string pName){
nom_ = pName;
}
unsigned int Teacher::getLevelAccess() const{
return(Employe::getLevelAccess() + accessTeacher_);
}
string Teacher::getClass() const{
return typeid(*this).name();
}
ostream& operator<<(ostream& os, const Teacher& pTeacher){
os << (pTeacher);
return os;
}
这是 Teacher.h :
static const unsigned int accesTeacher_ = 15;
最佳答案
我要做的是:仅定义一个
ostream& operator<<(ostream& os, const Employe& pEmploye)
{
return pEmploye.display(os);
}
对于层次结构的基础,
您可以在其中调用 protected 成员函数virtual display()
,该函数由每个派生类重写并且将显示委托(delegate)给该函数。这有时称为 NVI(非虚拟接口(interface))惯用语。它的工作原理如下:
class Employee
{
// ...
friend ostream& operator<<(ostream& os, const Employee& pEmployee)
{
return pEmployee.display(os);
}
protected:
virtual ostream& display(ostream& os) const
{
// implement it here
return os;
}
};
class Teacher: public Employee
{
// ....
protected:
ostream& display(ostream& os) const override
{
// implement it here
return os;
}
};
关于c++ - C++ 中运算符 << 的重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466572/