简体   繁体   English

c ++多态/纯虚函数

[英]c++ polymorphism/pure virtual function

I have a class called course. 我有一门课程叫做课程。 Course has a pointer to a base class called Assessment. 课程有一个指向名为Assessment的基类的指针。

class Course{
    char* courseName;
    float fee;

public:
    Assessment* assessment;
    Course();
    Course(Course&);
    Course(char*, float, Assessment *);
    ~Course();
    friend ostream& operator <<(ostream& os, Course&);
};

Strickly for testing purposes, in the constructor i'm assigning the Assessment pointer to an ExamAssessment(a sub-class) 严格用于测试目的,在构造函数中我将评估指针分配给ExamAssessment(子类)

Course::Course(){
    courseName = "something";
    fee = 0;
    assessment = &ExamAssessment(45);
}

My driver code looks like this 我的驱动程序代码如下所示

Course t = Course();
cout << *(t.assessment);

In assessment, Report is a pure virtual 在评估中,报告是纯粹的虚拟

virtual void Report() = 0;

The problem is when I cout the assessment, in the assessment overloaded operator '<<', I'm calling Report() 问题是当我进行评估时,在评估重载运算符'<<'时,我正在调用Report()

ostream& operator<<(ostream& os, Assessment& assessment){
    assessment.Report();
    os << "Course Grade: "<< assessment.grade << endl;
    return os;
}

But the Report is calling 'Assessments' Report instead of ExamAssessments Report. 但该报告称为“评估报告”而非“考试报告”。 Not sure where I'm going wrong with this(I'm fairly new to C++ inheritance) 不确定我在哪里出错了(我对C ++继承相当新)

In your Course::Course() you should never do that 在你的Course::Course()你永远不应该这样做

 assessment = &ExamAssessment(45);

You're taking the address of a temporary. 你拿的是临时的地址。 That will be invalid as soon as you're out of the constructor scope. 一旦你离开构造函数范围,那将是无效的。 And I think the compiler warned you ! 我认为编译器会警告你! That explain your crash unexpected behaviour when you're accessing assessment. 这可以解释您在访问评估时遇到的崩溃意外行为。

Do: 做:

 assessment = new ExamAssessment(45);

And as @Michael K. Sondej said delete it in the destructor. 正如@Michael K. Sondej所说,在析构函数中删除它。 Or use std::unique_ptr . 或者使用std::unique_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM