gpt4 book ai didi

c++ - 从 Circle 类 C++ 返回 bool 值

转载 作者:太空宇宙 更新时间:2023-11-04 13:44:03 26 4
gpt4 key购买 nike

我正在尝试使用 C++ 类返回一个 bool 值。它需要能够使用重载运算符 > 来检查圆 A 是否与圆 B 大小相同,我已将其添加为类中的公共(public)成员。在我的 int main 中,即使圆圈大小相同,它似乎也总是返回 false。

提前致谢。

圈类:

#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 main()

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

最佳答案

A.r4.0D.r 也是 4.0D > AA > D 都不为真。 > 检查实际是否大于。如果你想要大于等于使用 >= 代替。

关于c++ - 从 Circle 类 C++ 返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26636151/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com