Limitations of C++ Class Attributes and Reasons for Methods

Simple C++ program
Find the circumference and area of ​​a circle.
Data description:
Radius, circumference and area are all expressed by real numbers.
Data processing:
input radius r;
calculate circumference = 2 π r;
calculate area = π* r2;
output radius , Perimeter, area;

First look at a code and analyze it using memory analysis

#include<iostream>
using namespace std;//c++的命名空间
class circle
{
public:

	double r;

	double pi = 3.1415926;
	double area = pi*r*r;
	
};
int main()
{
	circle pi;
	cout << "请输入area" << endl;
	cin >> pi.r;
	cout << pi.area << endl;	//乱码
	system("pause");
	return 0;
}

This code prints garbled characters instead of the correct area of ​​the garden.
The reason can be explained by using the four-zone diagram of the memory. When the object of this class is created, the value of its attribute also exists, and then it is used without being changed by the class method, thus causing this result.

Below is the correct code to use the class method

#include<iostream.h> 
using name std;
class Circle
{  double radius ; //成员变量
  public : //类的访问控制
    void Set_Radius( double r ) { radius = r ; } //成员函数
    double Get_Radius()  { return  radius ; } //通过成员函数设置成员变量
    double Get_Girth()     { return  2 * 3.14f * radius ; } //通过成员函数获取成员变量
    double Get_Area()     { return  3.14f * radius * radius ; }
} ;
void main()
{ 
Circle A, B ; //用类定义对象
   A.Set_Radius( 6.23 ) ; //类的调用
   cout << "A.Radius = " << A.Get_Radius() << endl ;
   cout << "A.Girth = " << A.Get_Girth() << endl ;
   cout << "A.Area = " << A.Get_Area() << endl ;
   B.Set_Radius( 10.5 ) ;
   cout << "B.radius = " << B.Get_Radius() << endl ;
   cout << "B.Girth=" << B.Get_Girth() << endl ;
   cout << "B.Area = " << B.Get_Area() << endl ; 
}

The conclusion is
that the properties of the class, that is, the variable, will allocate memory when creating the object of this class so that there is a value,
and then we can manipulate this property through the method of the corresponding class later.

Guess you like

Origin blog.csdn.net/zw1996/article/details/85015315