Why C + + uses member functions

Source: Internet
Author: User

First look at the following code

1#include <iostream>2 3 using namespacestd;4 5 classCircle6 {7  Public:8     DoublePI =3.1415926;9     DoubleR;Ten     DoubleArea = pi*r*R; One  A     DoubleSetarea () -     { -         returnArea = pi*r*R; the     } - }; -  - intMain () + { - Circle C1; +cout <<"Please enter a radius:"<<Endl; ACIN >>C1.R; at  -cout << C1.area <<Endl; -cout << C1.setarea () <<Endl; -  -System"Pause"); -     return 0; in}

Operation Result:

Please enter radius:2.69149e+124314.159 Press any key to continue ...

As shown in the results of the operation, if the area areas are calculated with member variables, the result of the calculation is an error, because after the class circle has created the object C1, because the compiler does not actively call pi*r*r to calculate, but only from the memory to take the value, so the print out of the space is a very large garbage value.

Why C + + uses member functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.