我已经仔细研究了所有这些内容,并且对编写c++还是比较陌生,只是不知道自己缺少什么。有任何想法吗?
我的错误发生在第45行“return pi *(Radius * Radius);”。我几乎肯定该行的语法正确,但是为什么我会遇到编译错误。
#include <iostream>
#include <cstdlib>
using namespace std;
const double pi = 3.14159;
class Rectangle
{
protected:
float length, width;
public:
Rectangle(): length(0), width(0)
{
cout<<"Enter length: "; cin>>length;
cout<<"Enter width: "; cin>>width;
}
};
class Circle
{
protected:
float Radius;
public:
double radius;
Circle(): Radius(0)
{
cout<<"Enter Radius: "; cin>>Radius;
}
};
class Area : public Rectangle
{
public:
float getArea()
{
return length*width;
}
};
class Radius : public Circle
{
public:
float getRadius()
{
return pi * (Radius * Radius);
}
};
int main()
{
char choice;
for (int i = 0; i < 4; i++) //loop statement
{
cout << "Program to Find Area of a Square and Circle" << endl << //selection of which calculation to run
"Enter S for square square." << endl <<
"Enter C for circle." << endl <<
"Enter Q to Quit the program." << endl << endl <<
"Enter an option above: ";
cin >> choice;
switch(choice)
{
//Square option:
case 'S':
case 's': {
cout<<"Enter data for rectangle to find area.\n";
Area a;
cout<<"Area = "<<a.getArea()<<" square\n\n";
break;}
//Circle option:
case 'C':
case 'c': {
cout<<"Enter data for circle to find radius.\n";
Radius c;
cout<<"Radius = "<<c.getRadius()<<" meter\n\n";
break;}
//Quit option:
case 'Q':
case 'q': {
cout << "Thank you for using Area Application" << endl << endl;
system("PAUSE");
return EXIT_SUCCESS;
break;}
//default option binds to a non-selected choice function:
default:
cout << choice << " is not a valid selection." << endl;
cout << "Select a valid shape choice: S or C" << endl << endl;
break;
}
}
cout << "Press enter to continue ..." << endl;
return EXIT_SUCCESS;
}
谢谢
大卫
最佳答案
现在,我看到您在基类中有一个成员,该成员的名称Radius
与派生类中的名称相同,这就是导致错误的原因。解决方案是使用基类名称对其进行限定:
更改:
return pi * (Radius * Radius);
至:
return pi * (Circle::Radius * Circle::Radius);
这个附加的:
double radius;
可能来自一些测试-对吗?[编辑]
从设计的 Angular 来看,
class Radius : public Circle
的存在意义不大,仅使用Circle
来获得半径就可以了。关于c++ - '*'之前的预期主表达式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37591683/