C + + class member access rights

Source: Internet
Author: User

C + + uses public, protected, private three keywords to control the access rights of member variables and member functions, each of which represents a common, protected, private, called member access qualifier. The so-called access permission is that you can use the members in that class.

Java, C # Programmers note that the public, private, protected in C + + can only modify members of a class, cannot decorate classes, and classes in C + + do not share private.

Inside the class (within the code that defines the class), whether the members are declared public, protected, or private, they are accessible to each other and have no restrictions on access rights.

Outside of the class (outside the code that defines the class), members can only be accessed through the object, and only members of the public property can be accessed through the object, and members of the private and protected properties cannot be accessed.

The following is a Student class that demonstrates the access rights of members:

#include <iostream>using namespace std;//class declaration class Student{private:  //private    char *m_name;    int m_age;    Float m_score;public:  //Total    void SetName (char *name);    void setage (int age);    void SetScore (float score);    void Show ();};/ /member function definition void Student::setname (char *name) {    m_name = name;} void student::setage (int age) {    m_age = age;} void Student::setscore (float score) {    m_score = score;} The Age of Void Student::show () {    cout<<m_name<< "is <<m_age<<" and the result is "<<m_score<< Endl;} int main () {    //Create object on stack    Student Stu;    Stu.setname ("Xiao Ming");    Stu.setage (a);    Stu.setscore (92.5f);    Stu.show ();    Create an object on the heap    Student *pstu = new Student;    Pstu-SetName ("Li Hua");    Pstu, Setage (+);    Pstu, SetScore ();    Pstu, Show ();    return 0;}

C + + class member access rights

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.