【发布时间】:2022-01-11 18:23:36
【问题描述】:
我试图学习 C++ PL 中的运算符重载。我做了一个如下所示的练习。我想要做的是为每个派生类重载
班级员工:
class Employee {
public:
string name;
int id;
int exp_level;
double salary;
Employee() {
this->name = "";
this->id = 0;
this->exp_level = 0;
this->salary = 0.0;
}
~Employee() {
//WTF
}
virtual void calculateSalary() {
//CODE
}
virtual void registerX() {
//CODE
}
friend ostream& operator<<(ostream& os, const Employee& e) {
os << e.name << " " << e.exp_level << " " << e.id << " " << e.salary << endl;
return os;
}
};
技术类:
class Technical : public Employee {
public:
string profession;
Technical() {
this->profession = "";
}
~Technical() {
}
virtual void calculateSalary() {
//CODE
}
virtual void registerX() {
//CODE
}
friend ostream& operator<<(ostream& os, const Technical& e) {
os << e.name << " " << e.exp_level << " " << e.id << " " << e.salary << "Technical" << endl;
return os;
}
};
类工程师:
class Engineer : public Employee {
public:
Engineer() {
}
~Engineer() {
}
virtual void calculateSalary() {
//CODE
}
virtual void registerX() {
//CODE
}
friend ostream& operator<<(ostream& os, const Engineer& e) {
os << e.name << " " << e.exp_level << " " << e.id << " " << e.salary << "Engineer" << endl;
return os;
}
};
主要方法:
int main()
{
Employee* e = new Employee();
Employee* t = new Technical();
Employee* ee = new Engineer();
cout << *e << endl;
cout << *t << endl;
cout << *ee << endl;
}
输出:
0 0 0
0 0 0
0 0 0
【问题讨论】:
-
您遇到了什么错误或错误?
-
如果
<<的第二个操作数是Employee&,编译器的唯一选择是实现operator<<,它将Employee const&作为第二个参数。这适用于您打印的所有 3 个对象... -
给你的所有类一个虚函数
std::ostream put(std::ostream & os) const;,并在Employee的运算符重载中使用那个虚函数。这应该足够了。 -
@Bathsheba 我只是懒惰的 ATM ;-P
-
看看能不能申请Print Derived class object using a vector of Base class pointers referring this object。 Sam 在他的回答中展示的基本上与 πάνταῥεῖ 描述的方法相同。
标签: c++ class oop operator-overloading class-hierarchy