C++ 为什么这段代码没有输出所需的输出?
它始终为该区域输出“0”。我不知道如何在int r中计算面积C++ 为什么这段代码没有输出所需的输出?,c++,C++,它始终为该区域输出“0”。我不知道如何在int r中计算面积 // Define a class and use it to test out some math stuff #include <iostream> #include <cmath> using namespace std; class Circle { public: // function that calculates the area of a ci
// Define a class and use it to test out some math stuff
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
public:
// function that calculates the area of a circle
float circle_area(int r) {
area = 3.14 * (r*r);
return area;
} // end function circle_area
void display_msg() {
cout << "Area: " << circle_area(r) << endl;
} // end function display_msg
private:
float area;
int r;
}; // end class Circle
int main(void) {
int r;
Circle circle_calc; // create a Circle object named circle_calc
cout << "Radius of circle: ";
cin >> r;
circle_calc.display_msg();
}
从未设置成员变量Circle::r,main中的局部变量r通过cin设置,但从未使用
这样的东西可能是你想要的:
class Circle {
public:
Circle(int a_radius) : r(a_radius) {}
// function that calculates the area of a circle
float circle_area(int r) {
area = 3.14 * (r*r);
return area;
} // end function circle_area
void display_msg() {
cout << "Area: " << circle_area(r) << endl;
} // end function display_msg
private:
float area;
int r;
}; // end class Circle
int main(void) {
int r;
cout << "Radius of circle: ";
cin >> r;
Circle circle_calc(r);
circle_calc.display_msg();
}
变化:
面积不需要是Fred Larson所述的成员变量
r不需要传递给circle\u area成员函数,因为r是一个成员变量,所以circle\u area可以访问它
我怀疑OP不理解范围的概念。区域变量也不需要是类的成员。main中的r与类成员变量r不同
class Circle {
public:
// Constructor.
Circle(int a_radius) : r(a_radius) {}
// function that calculates the area of a circle
float circle_area() { return 3.14 * r * r; }
void display_msg() {
cout << "Area: " << circle_area() << endl;
}
private:
int r;
}; // end class Circle