【发布时间】:2017-09-09 18:16:46
【问题描述】:
我的 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;
}
形状.h
#ifndef SHAPE_H_INCLUDED
#define SHAPE_H_INCLUDED
class Shape {
public:
double getArea();
};
#endif // SHAPE_H_INCLUDED
形状.cpp
#include "shape.h"
Shape::Shape() {
area = 0;
}
double Shape::getArea() {
return area;
}
矩形.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
矩形.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()' 的定义 区域未在此范围内声明。
任何帮助将不胜感激。
【问题讨论】:
-
为什么要在 .h 和 .cpp 中声明类(相同)?将 .h 包含在 .cpp 中
-
错误表示该区域未声明。您在 shape.h 中的类声明没有声明属性“area”。矩形也不行。那么还有什么不清楚的呢?
-
通常你只有在你有某种形式的状态时才使用对象。 (除非您想学习一些东西并找到一个不好的示例用例)。越短越好。
double CircleArea( double r) { return 4 * atan(1.0) * r * r; }- 像这样的简单函数可以替换您的任何类。
标签: c++