You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中接收两个CourseGrade指针的maximumGrade函数如何实现

问题解答

maximumGrade 函数实现

直接实现两个指针对应成绩的比较逻辑即可,注意要访问指针指向对象的成绩属性,不能直接比较指针本身的内存地址:

CourseGrade* maximumGrade(CourseGrade* course0, CourseGrade* course1)
{
    // 增加空指针校验,避免非法访问崩溃
    if (!course0) return course1;
    if (!course1) return course0;
    // 比较两个对象的成绩,返回成绩更高的对象指针
    return course0->getGrade() >= course1->getGrade() ? course0 : course1;
}

适配3个课程找最高分的调用方法

你现在创建了3个课程对象,只需要嵌套调用maximumGrade就可以拿到三者中的最高分对象:

// 替换main中原有maximumGrade调用部分的代码
CourseGrade* maxCourse = maximumGrade(maximumGrade(ptrCourse0, ptrCourse1), ptrCourse2);

修正输出逻辑

原代码直接输出返回的指针会打印内存地址,需要调用getCourse()方法获取课程号输出:

cout << "The course with the maximum grade is: " << maxCourse->getCourse() << endl;

如果需要同时输出对应成绩,可以补充调用getGrade()方法。

内容的提问来源于stack exchange,提问作者Anthony Quinteros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:06:03