2014-10-29 2 views
1

Я пытаюсь вернуть логическое значение с использованием класса C++. Он должен иметь возможность проверить, имеет ли круг A тот же размер, что и круг B, с помощью оператора перегрузки>, который я добавил как открытый элемент в классе. В моем int main всегда кажется, что возвращает false, даже когда круги имеют одинаковый размер.Возвращение логического значения из класса Circle C++

Спасибо, заранее.

класс Circle:

#include <iostream> 
#include <cmath> 

using namespace std; 

//creating a constant pi that can't be changed 
const double pi = 3.14159265; 

class Circle 
{ 
    //defining the private memeber variables 
    private: 
      double radius, xpos, ypos; 

    //defining the public member variables 
    public: 
      //creating a constructor that takes all of the variables 
      Circle(double r, double xposition, double yposition) { 
       radius = r; 
       xpos = xposition; 
       ypos = yposition; 
      } 

      //creating a constructor that takes just the radius 
      Circle(double r) { 
       radius = r; 
       xpos = 0; 
       ypos = 0; 
      } 

      //creating a contructor that initialised everything to 0 
      Circle() { 
       radius = 0; 
       xpos = 0; 
       ypos = 0; 
      } 

      //defining the functions for radius, X-position, Y-position and area      
      double getRadius() {return radius;} 
      double getX() {return xpos;} 
      double getY() {return ypos;} 
      double getArea() {return pi*radius*radius;} 

      //creating an overaload operator + to add the various properties of a circle together 
      Circle operator+(Circle C) { 
       radius = sqrt(this->getRadius()*this->getRadius() + C.getRadius()*C.getRadius()); //calculates the radius from the area 
       xpos = (this->getX() + C.getX())/2.; //calculating the half way x position 
       ypos = (this->getY() + C.getY())/2.; //calculating the half way y position 
       return Circle(radius, xpos, ypos); 
      } 

      //created an overload operator << that outputs information about the circle in a consistent manor 
      friend ostream& operator<<(ostream& os, Circle C) { 
       return os << "radius = " << C.getRadius() << " at (x,y) = (" << C.getX() << "," << C.getY() << ")"; 
      } 

      bool operator>(Circle C) { 
       if (this->getRadius() > C.getRadius()) { 
        return true; 
       } 
       else { 
        return false; 
       } 
      } 
}; 

Int основной()

#include "Circle.hpp" 

using namespace std; 

int main() 
{ 
    //defining the circles A and B 
    Circle A(4.0,2.0,1.0); 
    cout << "Circle A: " << A << endl; 

    Circle B(4.0,5.0,6.0); 
    cout << "Circle B: " << B << endl; 

    //Adds A and B using the overload operator + 
    Circle C = A + B; 

    //Outputs the formatted text using the overload operator << 
    cout << "Circle C: " << C << endl; 


    bool test; 
    Circle D(4.0,2.0,1.0); 

    if (A > D) { 
     test = false; 
    } 
    else if (D > A) { 
     test = false; 
    } 
    else { 
     test = true; 
    } 

    cout << boolalpha << test << endl; 

    return 0; 
} 
+1

Заметим, что в C++ вы бы традиционно перегрузки 'operator <' для определения порядка. Нет особой причины, по которой вы * не могли бы использовать 'operator>' вместо этого, но все алгоритмы в стандартной библиотеке (для одного примера) используют 'operator <' вместо 'operator>'. –

ответ

0

"В моей ИНТ основном она всегда кажется, вернуться ложным, даже если круги имеют одинаковый размер"

It обязательно вернет значение false, если круг имеет тот же размер, что и ваше состояние: -

if (this->getRadius() > C.getRadius()) 
     return true; 

все, кроме этого, вернет ложь. Если вы хотите, чтобы вернуться верно, когда ваш круг имеют одинаковый размер, то сделать это: -

if (this->getRadius() < C.getRadius()) 
     return false; 
    else 
     return true; 

РЕДАКТИРОВАНИЕ В ОТВЕТ НА ОТЗЫВ: -

Тогда, возможно, вы можете использовать перечисление, если хотите, чтобы проверить три различных сценария : -

if (this->getRadius() > C.getRadius()) 
    return ENUM_GREATER; 
else if (this->getRadius() == C.getRadius()) 
    return ENUM_EQUAL; 
return ENUM_LESSER; 
+1

Я думаю, что он означает, что 'test' является' false', что происходит только в том случае, если 'A> D' или' D> A'. –

+0

Я должен вернуть true, когда this-> getRadius()> C.getRadius() – thewire247

0

A.r является 4.0. D.r также 4.0. Ни D > A, ни A > D - это правда. > проверяет, действительно ли больше. Если вы хотите использовать большее или равное значение >=.

0

Ваш operator+ изменяет левый операнд. Таким образом, эта строка изменяет A:

Circle C = A + B; 

(включая radius члена). Итак, к тому времени, когда вы сравниваете A с D, Aradius больше не 4.0.

operator+ может быть изменен следующим образом, чтобы это исправить:

Circle operator+(const Circle& C) const { 
    double r = sqrt(this->getRadius()*this->getRadius() + C.getRadius()*C.getRadius()); //calculates the radius from the area 
    double x = (this->getX() + C.getX())/2.; //calculating the half way x position 
    double y = (this->getY() + C.getY())/2.; //calculating the half way y position 
    return Circle(r, x, y); 
} 
+0

Спасибо, что работает :-). Есть ли способ изменить код, чтобы он не менял A – thewire247

+0

@ thewire247: см. Править –

+0

Спасибо, что сработало !! – thewire247

0

Когда вы делаете следующее вы меняете значение радиуса а в

Circle C = A + B 
Смежные вопросы