我在C++程序中遇到問題。我需要找到正方形,圓形和矩形的區域。我把所有東西都放在圓形和正方形中,但矩形和形狀(繼承結構)給了我上述問題。我一直在試圖解決這個問題,因此如果有人能幫助我,我會非常感謝它。我的代碼是:在C++中使用繼承的正方形,圓形和矩形的區域
main.cpp
#include <iostream>
#include "Circle.h"
#include "Square.h"
#include "Rectangle.h"
using namespace std;
int main()
{
double radius = 0;
double length = 0;
double width = 0;
Square square;
Circle circle;
Rectangle rectangle;
int option;
cout << "Calculating the Area" << endl << endl;
do
{
cout << "Pick a shape in which you would like the area of:" << endl;
cout << "1: Square" << endl;
cout << "2: Circle" << endl;
cout << "3: Rectangle" << endl;
cout << "4: Exit" << endl;
cout << "Please enter your choice: ";
cin >> option;
switch(option)
{
case 1:
{
cout << endl;
cout << "Please enter the length of one side of the square: " << endl;
cin >> length;
Square square(length);
cout << "The area of the square is: " << square.getArea() << "\n\n";
break;
}
case 2:
{
cout << endl;
cout << "Please enter the radius of the circle: ";
cin >> radius;
circle.setRadius(radius);
cout << "The area of the circle is: " << circle.getArea() << "\n\n";
break;
}
case 3:
{
cout << endl;
cout << "Please enter the length of one side of the rectangle: ";
cin >> length;
rectangle.setLength(length);
cout << "Please enter the width of one side of the rectangle: ";
cin >> width;
rectangle.setWidth(width);
cout << "The area of the rectangle is: " << rectangle.getArea();
}
}
}
while (option != 4);
cout << "Bye!" << endl;
}
shape.h
#ifndef SHAPE_H_INCLUDED
#define SHAPE_H_INCLUDED
class Shape {
public:
double getArea();
};
#endif // SHAPE_H_INCLUDED
shape.cpp
#include "shape.h"
Shape::Shape() {
area = 0;
}
double Shape::getArea() {
return area;
}
rectangle.h
#ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED
#include <iostream>
#include "shape.h"
class Rectangle : public Shape
{
public:
Rectangle (double length = 0, double width = 0);
double getLength = 0;
double getWidth = 0;
void setLength(double length);
void setWidth(double width);
double getArea();
private:
double length;
double width;
};
#endif // RECTANGLE_H_INCLUDED
rectangle.cpp
#ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED
#include <iostream>
#include "shape.h"
class Rectangle : public Shape
{
public:
Rectangle (double length = 0, double width = 0);
double getLength = 0;
double getWidth = 0;
void setLength(double length);
void setWidth(double width);
double getArea();
private:
double length;
double width;
};
#endif // RECTANGLE_H_INCLUDED
我只包含了我遇到的問題。看到我如何知道我的其他人工作,這是我上週做的一個程序的重寫。每次我嘗試構建它時,都會遇到這兩個錯誤。
隱式聲明的Shape :: shape()' area的定義未在此範圍內聲明。
任何幫助將不勝感激。
爲什麼要在.h和.cpp中聲明類(相同)?將.h添加到.cpp – Yunnosch
錯誤表示該區域未聲明。 shape.h中的類聲明不聲明屬性「area」。矩形也不是。那麼什麼不清楚? – Yunnosch
通常情況下,如果你有某種形式的狀態,你只能使用對象。 (除非你想學習一些東西並找到一個不好的例子用例)。越短越好。 'double CircleArea(double r){return 4 * atan(1.0)* r * r; }'' - 這樣簡單的函數可以替換你的任何類。 – BitTickler