我如何分割我的头和实现文件,使一切工作在一起正确?



我必须为类"Rectangle."创建一个带有头文件、实现文件和测试文件的c++程序。但是,我不确定如何正确地分离头类,我认为这就是为什么我在测试类中遇到错误的原因。我使用IDE代码来完成这项任务。

我的头文件:

#ifndef RECTANGLE_H
#define RECTANGLE_H
class rectangle {
private:
double width;
double height;

public: 
rectangle();
rectangle(double inputWidth, double inputHeight);
double getWidth();
double getHeight();
double getArea();
double getPerimeter();
void printRectangle(string objectName);
}
#endif

我在声明类的行上得到一个错误消息,它说,&;Expected ';'在顶级声明符之后。

我没有在我的。cpp实现文件中显示任何错误,但我在测试器文件中得到了许多错误。它没有意识到我试图创建矩形类的对象,或者至少在我试图调用参数化构造函数时没有意识到。当我这样做的时候,它给了我一个错误'使用未声明的标识符'矩形',';然后在应该接受形参的对象上,它会询问我是否打算键入原始的默认对象。

下面是文件开头和(尝试)创建对象的代码:

#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "rectangle.h"
#include "rectangle.cpp"
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);

然后,我在每一行试图调用使用参数化构造函数创建的对象的方法的代码中都得到一个错误,说"使用未声明的标识符'herRectangle '"。由于某些原因,我没有在默认矩形的代码行上得到这些错误消息。

下面的代码显示了调用'herRectangle'对象的方法:

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();

任何和所有的帮助将非常感激!如果你还想让我展示什么来帮助你,请告诉我。对不起,如果我的格式是有点不稳定,以及,我是新的论坛。

很简单。首先定义头文件.h.hpp

Rectangle.hpp

#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
//Method declaration
}; // Notice samicolon
#endif

Rectangle.cpp

#include "Rectangle.hpp"
// Method implementation 

,然后在main.cpp

#include "Rectangle.hpp"
int main{
Rectangle rect;
}

这是你如何区分你的定义和实现。

相关内容

最新更新