2016-06-02 5 views
1

Я просмотрел все эти данные и относительно новичок в кодировании C++ и просто не знаю, чего у меня нет. Есть идеи?ожидаемое первичное выражение перед '*'?

Моя ошибка возникает в строке 45 "return pi * (Радиус * Радиус);" Я почти уверен, что синтаксис для этой строки правильный, но почему я получаю ошибки компиляции.

#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; 
} 

Thanks Дэвид

+3

Я думаю, что здесь есть некоторые проблемы с точки зрения понимания дизайна ООП. Почему «Радиус» наследует «Круг»? – Smeeheey

+0

Этот код очень смущен. Класс 'Circle' имеет как члены класса« Радиус », так и« радиус ». Конструктор инициализирует частный «Радиус». Публичный 'radius' не инициализируется вообще. –

ответ

2

Теперь я вижу, у вас есть элемент в базовом классе, который имеет имя Radius который является таким же, как и в производном классе, это то, что вызывает ошибку. Решение состоит в том, чтобы квалифицировать его с именем базового класса:

изменение:

return pi * (Radius * Radius); 

к:

return pi * (Circle::Radius * Circle::Radius); 

это Additonal: double radius;, вероятно, из какого-тестирования - не так ли?

[править]

С точки зрения дизайна о имеющейся class Radius : public Circle имеет мало смысла, она должна быть тонкой, чтобы просто использовать Circle, чтобы получить его radious.

+0

Спасибо за комментарии, да, я пытался выполнить проверку проверки и забыл ее удалить. Я также не видел обратную ссылку на «круг», который был уже публичным. Я все еще многому научился делать на производных классах и наследовании. – haynstyle

+0

@haynstyle не проблема, я обычно никогда не использую переменные, начинающиеся с буквы верхнего регистра, те имена, которые я резервирую для классов. Я обнаружил, что вы также можете использовать 'использование Circle :: Radius;' в классе класса, чтобы заставить Radius ссылаться на переменную базового класса, но этот aproach имеет и другие недостатки. – marcinj

+0

Полезно знать, это очень полезно, и я возьму этот вход и применил его к моему следующему проекту. Еще раз спасибо. – haynstyle

0
#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;} 
    float getArea(){return length*width;} 
}; 

class Circle 
{ 
    protected: 
    float Radius; 
public: 
    Circle(): Radius(0)  {cout<<"Enter Radius: "; cin>>Radius;} 
    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"; 
     Rectangle a; 
     cout<<"Area = "<<a.getArea()<<" square\n\n"; 
     break;} 

    //Circle option: 
    case 'C': 
    case 'c': { 
     cout<<"Enter data for circle to find radius.\n"; 
     Circle 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; 
} 
Смежные вопросы