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

C++矩形面积类继承代码VS编译通过GFG编译报错求助

问题现象
  • 编写C++代码完成矩形面积类继承编程题,VS Code本地环境编译运行正常
  • 提交到在线判题平台时触发编译错误,核心报错提示为int main() previously defined here,无法定位问题原因
原提交代码
#include <iostream>

using namespace std;
/*
* Create classes Rectangle and RectangleArea
*/
int l,b, result;

class Rectangle
{
   public:
      void display()
      {
        cout<<l <<" "<< b<<endl;
      }
};

class RectangleArea : public Rectangle
{
  public:
    void read_input()
    {
        cin >> l >> b;
    }
    void display()
    {
        result = l* b;
        cout<<result;
    }
};

int main()
{
 /*
 * Declare a RectangleArea object
 */
 RectangleArea r_area;

  /*
  * Read the width and height
  */
  r_area.read_input();

/*
 * Print the width and height
 */
  r_area.Rectangle::display();

  /*
  * Print the area
  */
  r_area.display();

   return 0;
  }
错误原因
  1. main函数重复定义:这类在线编程判题平台的后端已经内置了完整的main函数逻辑,负责读取用例、调用你实现的类、校验输出。你在提交的代码里额外写了一份main函数,链接阶段就会出现符号重复定义的报错。本地运行时只有你自己写的一份main,所以不会触发这个问题。
  2. 类设计不符合封装要求:你把矩形的长、宽、计算结果都定义成了全局变量,没有作为类成员封装,不符合题目面向对象继承的考察要求,即使解决了main重复的问题,也可能因为设计不符合要求判错。
修复方案
  • 删除你自己编写的整段int main()代码块,不需要在提交内容里实现主函数
  • 把全局变量l、b移动到Rectangle类的protected成员域,供派生类RectangleArea访问,去掉不必要的全局result变量,计算面积时直接输出乘积即可
  • 修正后的可提交代码参考:
#include <iostream>

using namespace std;

class Rectangle
{
protected:
    int l, b;
public:
    void display()
    {
        cout << l << " " << b << endl;
    }
};

class RectangleArea : public Rectangle
{
public:
    void read_input()
    {
        cin >> l >> b;
    }
    void display()
    {
        cout << l * b;
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 16:33:29