About static member variables in C + +

Source: Internet
Author: User

Here are 1 examples to explain:

1#include <iostream>2#include <string>3 using namespacestd;4 5 6 classStudent7 {8     Private://declare a variable as private9     intnum;Ten     stringname; One     intMath; A     int中文版; -     intTotal ; -     Static stringteacher; the     voidcacu_total (); -      -      Public: -     voidInput_stu (); +     voidOutput_stu (); - }; +  AString student::teacher = "Xiaoming"; at intMainintARGC,Char*argv[]) - { - student STU1,STU2; -Student *Pstu; -Pstu =Newstudent; - Stu1.input_stu (); in Stu2.input_stu (); -Pstu->Input_stu (); to      + Stu1.output_stu (); - Stu2.output_stu (); thePstu->Output_stu (); *     DeletePstu; $     return 0;Panax Notoginseng}

For the above code explanation: defines a variable of 2 classes STU1 STU2 how for their member variable

For example, STU1 's num name math and other variables such as STU2 's num name math are different variables

For teacher This member variable, STU1 and STU2 are the same, that is, changing the teacher value in STU1 stu2 the value of teacher will also change

Because they are occupying the same piece of memory.

It is possible to understand that a static member variable is equivalent to defining a global variable in a class that is not stored in the data of each object and that the entire class has only 1 copies

It is also important to note that static member variables, in addition to being declared in a class, must be explicitly defined externally

This is the sentence above:

String student::teacher = "Xiaoming";

About static member variables in C + +

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.