класс — C ++: при использовании суперкласса и подкласса значение из простого расчета площади возвращает 3.47668e-310 независимо от того, что я положил для вычисления из

Я пишу программу на C ++ для моей программной логики и класса дизайна. Я новичок Мы должны написать программу, которая вычисляет площадь формы, используя суперкласс (Shape) и подклассы (Circle, Rectangle и Triangle). Возвращаемое мне значение всегда равно 3.47668e-310, независимо от того, какие значения я задаю для радиуса, длины, ширины, основания, высоты. Может кто-нибудь помочь мне с тем, что я делаю неправильно?

Во-первых, мой суперкласс выглядит так:

#include <iostream>

using namespace std;

#ifndef SHAPE

#define SHAPE

class Shape
{
private:
// Field declaration to hold calculated area from subclass
double shapeArea;

public:
// Member functions
// Mutator
void setArea(double anArea)
{
shapeArea = anArea;
}

// Accessor
double getArea()
{
return shapeArea;
}
}; // End Shape class
#endif

Подклассы круга выглядят так:

#include <iostream>
#include <math.h>

using namespace std;

const double PI = 3.14159;

// Function prototype
void calcArea(double &);

class Circle : public Shape
{
private:
// Fields
double radius;
double area;

void calcArea(double &radius)
{
area = pi * pow(radius,2);
}

public:
// Constructor sets the area
Circle(double aRadius)
{
// Call calcArea, passing aRadius
calcArea(aRadius);

//Local variable for area
double anArea;
area = anArea;

//Call inherited setArea function to set the area
setArea(anArea);
}
}; // End Circle class

И мое главное это:

#include <iostream>

#include "ShapeClass.cpp"#include "CircleClass.cpp"#include "RectangleClass.cpp"#include "TriangleClass.cpp"
using namespace std;

//Function prototype
void displayMenu(int &);

// Global variables
const int EXIT_CHOICE = 4;
const int MIN_CHOICE = 1; // Used to compare if selection is less than 1
// for displayMenu method

int main()
{
// Declare selection variable
int selection;

// Declare variable to hold area
double shapeArea;

//Declare variables to hold user input
double circleRadius, rectangleLength, rectangleWidth, triangleBase, triangleHeight;

//Create objects from classes: Circle, Rectangle, Triangle
Circle areaCircle(circleRadius);
Rectangle areaRectangle(rectangleLength, rectangleWidth);
Triangle areaTriangle(triangleBase, triangleHeight);

// Get selection from user and verify they did not enter
// option to end the program
do
{
// Display menu
displayMenu(selection);

// Based on user selection, prompt user for required
// measurements of shape and return the area
switch (selection)
{
case 1:
// Prompt user for radius of the circle
cout << "Enter radius of circle." << endl;
cin >> circleRadius;

cout << "The area of the circle is "<< areaCircle.getArea() << endl << endl;
break;
case 2:
// Prompt user for the length of the rectangle
cout << "Enter the length of the rectangle." << endl;
cin >> rectangleLength;

// Prompt user for the width of the rectangle
cout << "Enter the width of the rectangle." << endl;
cin >> rectangleWidth;

cout << "The area of the rectangle is "<< areaRectangle.getArea();
cout << endl << endl;
break;
case 3:
// Prompt user for the length of the base of the triangle
cout << "Enter the length of the base of the triangle." << endl;
cin >> triangleBase;

// Prompt user for the height of the triangle
cout << "Enter the height of the triangle." << endl;
cin >> triangleHeight;

cout << "The area of the triangle is "<< areaTriangle.getArea() << endl << endl;
break;
case 4:
cout << "Goodbye!" << endl;
cout << endl << endl;
break;
}
} while (selection != EXIT_CHOICE);

system("Pause");
return 0;
}// End main()

void displayMenu(int &select)
{
// Prompt user for shape for which they want
// the area calculated
cout << "Geometry Calculator" << endl;
cout << "1. Calculate the area of a Circle." << endl;
cout << "2. Calculate the area of a Rectangle." << endl;
cout << "3. Calculate the area of a Triangle." << endl;
cout << "4. End the program." << endl;
cout << "Enter your selection: ";
cin  >> select;

// Validate user selection
while (select < MIN_CHOICE or select > EXIT_CHOICE)
{
cout << "That is an invalid selection." << endl;
cout << "Enter 1, 2, 3, or 4 to end the program." << endl;
cin >> select;
}
}// End displayMenu()

Надеюсь, это не так уж и много. Спасибо!

0

Решение

Вы перезаписываете область мусором.

двойная зона;
area = anArea;

Избавьтесь от этих строк и передайте область в setArea.

0

Другие решения

В методе calcArea()член area уже назначен. Вы должны удалить строки

     double anArea;
area = anArea;

Более того, когда вы звоните по наследству setArea() а также getArea() методы, базовый класс private член shapeArea модифицируется, но shapeArea недоступен производным классам из-за public inheritance,

Чтобы сделать shapeArea доступны экземплярами производного класса, вам нужно объявить его как protected и удалите лишний элемент area в производных классах и изменить связанный метод calcArea():

   void calcArea(double &radius)
{
shapeArea = pi * pow(radius,2);
}
0