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

C++拆分Rectangle类头/实现/测试文件时编译报错如何解决?

C++ Rectangle类拆分问题修复方案

头文件错误修复

你当前头文件有两个核心语法错误:

  1. 类定义结束后缺失结尾分号,这就是Expected ';' after top level declarator报错的直接原因
  2. printRectangle成员函数用到了string类型,但没有引入<string>头文件,也没有指定std命名空间,头文件不要直接写using namespace std,避免命名空间污染
    修复后的rectangle.h代码如下:
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <string>

class rectangle {
private:
    double width;
    double height;
public: 
    rectangle();
    rectangle(double inputWidth, double inputHeight);
    double getWidth();
    double getHeight();
    double getArea();
    double getPerimeter();
    void printRectangle(std::string objectName);
};

#endif

测试文件错误修复

测试文件的错误绝大多数是头文件语法错误导致的连锁问题,另外你还有两个错误操作:

  1. 不要引入实现文件#include "rectangle.cpp",C++编译规则是头文件提供声明,cpp文件单独编译后链接,引入cpp会导致重复定义错误
  2. 调用printRectangle时没有传入要求的string类型参数,和类声明的函数签名不匹配
    修复后的测试代码核心部分如下:
#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "rectangle.h"

using namespace std;

int main() {
    double inputWidth;
    double inputHeight;

    rectangle myRectangle;
    cout << "Enter the width of the rectangle:" << endl;
    cin >> inputWidth;
    cout << "Enter the height of the rectangle:" << endl;
    cin >> inputHeight;
    rectangle herRectangle(inputWidth, inputHeight);

    cout << "herRectangle" << endl;
    cout << "------------" << endl;
    cout << "Width: " << herRectangle.getWidth() << endl;
    cout << "Height: " << herRectangle.getHeight() << endl;
    cout << "Area: " << herRectangle.getArea() << endl;
    cout << "Perimeter: " << herRectangle.getPerimeter() << endl;
    herRectangle.printRectangle("herRectangle"); // 补全入参
    return 0;
}

实现文件(rectangle.cpp)规范

实现文件需要先引入头文件,再写成员函数的实现,参考写法:

#include "rectangle.h"
#include <iostream>

rectangle::rectangle() : width(0), height(0) {}

rectangle::rectangle(double inputWidth, double inputHeight) 
    : width(inputWidth), height(inputHeight) {}

double rectangle::getWidth() { return width; }
double rectangle::getHeight() { return height; }
double rectangle::getArea() { return width * height; }
double rectangle::getPerimeter() { return 2 * (width + height); }
void rectangle::printRectangle(std::string objectName) {
    std::cout << "Rectangle name: " << objectName << std::endl;
}

CodeLite编译配置注意事项

要保证rectangle.cpp和测试文件都被加入到当前项目的编译列表中,不要单独只编译测试文件,否则会出现链接时找不到函数实现的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:00:03