I need to calculate the radius of the circle in the code.
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
float radius;
const float PI=3.14;
public:
Circle(float radius){
}
Circle getRadius()
{
return radius;
}
Circle setRadius(float radius)
{
this->radius = radius / PI;
return radius;
}
float Area()
{
return radius*radius*PI;
}
float Perimeter()
{
return 2*radius*PI;
}
int equal()
{
return Area()==Perimeter();
}
};
int main() {
float r;
cin >> r;
Circle c(r);
cout << c.Perimeter() << endl;
cout << c.Area() << endl;
cout << c.equal() <<endl;
return 0;
}
i tried to use pointers but i cannot figure it out.
In
Circle(float radius){
}
a parameter with the same name as a member variable is not that member variable. Instead, it shadows the member variable, effectively replacing it unless you know where to look. Passing a value into a parameter named radius
will not change the value of the member variable named radius
, and this leaves the member radius
uninitialized.
This means that
float Perimeter()
{
return 2*radius*PI;
}
and the other functions, excluding setRadius
, operate on an uninitialized variable and the results will be undefined.
A possible solution is to ensure the member radius
is initialized to the value of the parameter radius
.
You cannot simply
Circle(float radius){
radius = radius;
}
because there is only one radius
, the member has been shadowed, so the parameter radius
assigns its value to itself. This is legal code so it compiles, but often the compiler will issue a warning.
Instead use
Circle(float radius) : radius(radius) {
}
This makes use of the Member Initializer List , one of the most important (and seemingly least-taught) features of the C++ programming language. It allows you to safely reuse the term radius
because the first radius
must be the member radius
.
You could also
Circle(float radius) {
this->radius = radius;
}
to explicitly use the member radius
, but for more complicated members this approach can be inefficient. All member variables and base classes are initialized before entering the body of the constructor. Afterward the best you can do is assign. This means the member will be default-initialized (if a default constructor exists; if it doesn't you must use the member initializer list), then a temporary variable must be constructed and this temporary is then assigned to the member. potentially a lot of extra work for no benefit.
Side note:
Keep an eye on the this->radius = radius / PI;
in setRadius
. It is unusual and probably a bug.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.