C++ Note 007: The Fallible Model - Why Member Functions Are Needed in Classes

Look at the source code first, it cannot be compiled in the VS2010 environment, but it can be compiled and passed in the VS2013 environment, and it can be run, but the running result is not what we expect.

 

When the object c1 is initially defined through the MyCircle class, memory space is allocated for the object, r is not initialized, its value is garbled, pi is 3.1415926, and area is garbled.

[cin>>c1.r] This statement assigns value to c1.r, assuming it is 10, and then executes [cout<<c1.area<<endl]. Let’s see, when cout is executed , c1.area is taken from the memory space The value of , this value has been determined to be a garbled value when the object is defined, and the [double area=pi*r*r] statement will not be executed here, so the garbled character is output.

If you want to get the correct result, you need member functions, in which the calculations are performed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124220&siteId=291194637