【发布时间】:2021-11-13 18:48:55
【问题描述】:
在 student.h 文件中
class Student {
protected:
string Name;
int Stu_num;
public:
virtual void print() = 0;
// constructor...
}
class Grad_Student: public Student {
private:
string Lab;
public:
void print();
// constructor...
}
class Undergrad_Student: public Student {
private:
string Major;
public:
void print();
// constructor...
}
在 student.cpp 文件中
bool operator == (const Student& x, const Student& y) {
if (typeid(x) != typeid(y)) return false;
else // dosomething..
}
我想比较 Student 类的孩子;研究生和本科。 在 main.cpp 中,当我比较两个学生班级时,它不起作用..
Grad_Student grad1 = Grad_Student("Max", 11, "Hubo");
Student *std1 = &grad1;
Grad_Student grad2 = Grad_Student("Max", 11, "Hubo");
Student *std2 = &grad2;
cout << (std1 == std2) << endl; // it always prints 0.
cout << (*std1 == *std2) << endl;
// I think this line should work, but makes error.
// error: invalid operands to binary expression ('Student' and 'Student')
我应该在学生课上重载 operator== 吗? 给我一个提示...
【问题讨论】:
-
你得到什么错误?
-
“它不起作用” 请描述您所询问的问题。否则,我们必须猜测什么不起作用。
-
不应该
Undergrad_Student派生自Student? -
正如您发布的那样...目前您的覆盖运算符根本不返回任何内容。你可能希望它做一些事情......比如比较学生对象的数量和名称,然后返回 true 表示它们相同或返回 false 表示它们不同。
-
@gun bos:您的代码似乎有多个严重错误,其中任何一个都可以解释问题。请阅读 Wbuck 的response。如果它回答了您的问题,请“投票”并“接受”答案。
标签: c++ class inheritance overloading abstract