【发布时间】:2016-12-07 15:42:04
【问题描述】:
我是编码新手,我正在尝试编写一个具有多态性但我的矩形部分不起作用的程序。我试图在所有三个文件中添加变量以适应它,但我不断收到错误。下面的代码是我解决此问题的最新尝试。我现在得到的错误是“r”中的成员“区域”的[错误]请求,这是非类类型“float”和“r”中的参数,这是非类类型“float”。在这一点上,我不知道如何解决这个问题。可以的话请帮忙!
Main.cpp
#include <iostream>
#include "shape.h"
#include "shape.cpp"
using namespace std;
int main() {
float r, a, b, a1, b1;
cout<<"This program will ask you to input some data in order to find the area and the parameter of 3 shapes."<<endl;
cout<<"\nInput the circles radius --everything should be in inches (i.e 5):";
cin>>r;
Circle c(r);
cout<<"\nPlease input two side of the Right Triangle excluding the hypotenuse-- everything should be in inches( i.e 5 5): ";
cin>>a>>b;
RTriangle rt(a,b);
cout<<"\nPlease input two side of the Rectangle -- everything should be in inches( i.e 5 5): ";
cin>>a>>b;
Rectangle r(a1,b1);
cout<<"\n\nThe Circles Area is:"<<c.area()<<" inches, The Parameter is:"<<c.parameter()<<" inches"<<endl;
cout<<"The Rectangle Area is:"<<r.area()<<" inches, The Parameter is:"<<r.parameter()<<endl;
cout<<"The Right Triangle Area is:"<<rt.area()<<" inches, The Parameter is:"<<rt.parameter()<<" inches"<<endl;
cout<<"Thanks once agin for using this program for your AREA and PARAMETER needs!"<<endl;
system ("PAUSE");
return 0;
}
形状.cpp
#include"shape.h"
Shape::Shape(){
sideA = sideB = 0;
}
Shape::Shape(int a, int b){
sideA = a;
sideB = b;
}
//these will get overrided
float Shape::area(){return 0;}
float Shape::parameter(){return 0;}
//rectangle definations
Rectangle::Rectangle(float a, float b):Shape(a,b){
//calling parent class constructor
}
float Rectangle::area(){
return sideA*sideB;
}
float Rectangle::parameter(){
return 2*(sideA+sideB);
}
//right triangle definations
RTriangle::RTriangle(float h, float w):Shape(h, w){
}
float RTriangle::area(){
return 0.5*sideA*sideB;
}
float RTriangle::parameter(){
float hyp = sqrt(sideA*sideA + sideB*sideB);
return sideA + sideB + hyp;
}
//circle definations
Circle::Circle(float r){
sideA = r;
}
float Circle::area(){
return 3.14 * sideA * sideA;
}
float Circle::parameter(){
return 2 * 3.14 * sideA;
}
形状.h
#ifndef SHAPES
#define SHAPES
#include<cmath>
class Shape {
protected:
float sideA, sideB;
float radius;
public:
Shape();
Shape(int,int);
virtual float area();
virtual float parameter();
};
class Rectangle : public Shape{
public:
Rectangle(float a, float b);
float area();
float parameter();
};
class RTriangle : public Shape{
public:
RTriangle(float h, float w);
float area();
float parameter();
};
class Circle : public Shape{
public:
Circle(float r);
float area();
float parameter();
};
#endif
【问题讨论】:
标签: c++ constructor compiler-errors polymorphism