如何使用类获取矩形面积?

How to get area of rectangle using class?

本文关键字:何使用 获取      更新时间:2023-10-16

我的任务是使用class计算矩形的面积和周长。输入函数应该在类内。到目前为止,我编写了代码,但似乎有一些我无法检测到的错误。

一些帮助将不胜感激。

矩形.h

#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
public:
int width, length;
Rectangle();
Rectangle(int width1,int length1);
void getRectangle();
int getArea();
int getPerimeter();
};
#endif // RECTANGLE_H

矩形.cpp

// oporer ta class
#include<iostream>
#include "rectangle.h"
Rectangle::Rectangle()
{
width=0;
length=0;
}
Rectangle::Rectangle(int width1,int length1)
{
width=width1;
length=length1;
}
void Rectangle::getRectangle()
{
cin>>width>>length;
}
int Rectangle::getArea()
{
return (width*length);
}
int Rectangle::getPerimeter()
{
return (width+length)*2
}
// oporer ta rectangle cpp 

主.cpp

#include <iostream>
#include "rectangle.h"
using namespace std;
int main()
{
Rectangle paraFirst();
paraFirst.getRectangle();
return 0;
}
// main fucntion

假设#include在您的本地设置中工作,我在这里看到两个拼写错误:

  • cin>>width>>length;必须std::cin >> width >> length;
  • return (width+length)*2后缺少分号

可能是主要问题:

Rectangle paraFirst();

被解析为不带参数并返回Rectangle的函数的声明。另请参阅最烦人的解析。要调用默认构造函数,只需使用

Rectangle paraFirst;    

Rectangle paraFirst{};