C + + language Learning (iii)--Encapsulation (encapsulation)

Source: Internet
Author: User
Tags access properties

C + + language Learning (iii)--Encapsulation (encapsulation) package Introduction

In process-oriented programming, such as C language, data and related operation functions of data are separate individuals; in object-oriented programming such as C + +, data and data related operations are designed as objects, which consist of attributes (data) and operations (functions), which together form an object entity (that is, a class entity). Object-oriented programming makes the program more modular, easier to read and write, and improves code reuse to a higher level.
In object-oriented programming, data and data operations are encapsulated for objects. Encapsulation can hide implementation details, allowing code to be modularized, to surround processes and data, and to access data only through defined interfaces.
Encapsulation is a model for providing services externally, and the encapsulation model is an individual abstraction of everything in the world.
The encapsulated access properties are as follows:
Accessing an Attribute Property object inside an object
Public has access to accessible
Protected protection can be accessed not accessible
Private access is not accessible
In C, all behaviors and properties in a struct are public (the default), they can use interfaces, they can access their internal data directly, and no internal data is masked.
In the C + + language, the packaging features of C language are enhanced, and the struct and class can specify the way of accessing behavior and attributes, open data internally, and externally, and provide interfaces to external data.

Ii. encapsulation of the C language

In the C language, encapsulation is usually done using modularity.
Stack's C language implementation:

#include <stdio.h>#include <string.h>typedef struct stack{    char space[1024];    int top;}stack;void stack_init(stack *st){    st->top = 0;    memset(&st->space, 0, sizeof(st->space));}int is_empty(stack *st){    return st->top == 0;}int is_full(stack *st){    return st->top == 1024;}char pop(stack *st){    return st->space[--st->top];}void push(stack *st, char c){    st->space[st->top++] = c;}int main(void){    stack st;    stack_init(&st);    unsigned int i;    for(i = ‘a‘; i < (‘z‘ + 1); i++)    {        if(!is_full(&st))            push(&st, i);    }    for(i = ‘a‘; i < (‘z‘ + 1); i++)    {        printf("%c\n", pop(&st));    }    return 0;}

The data members of the encapsulated struct in the C language can be modified by external calls.

Three, C + + language encapsulation 1, C + + language encapsulation

The C + + language reinforces the encapsulation of the language and defines the level of access to properties and behaviors in the class's notation.
In the C + + language, a variable that represents a Class property is a member variable, and a function that represents the behavior of a class is a member function. In the C + + language, you can define access levels for member variables and member functions of a class.
Public: Member variables and member functions of a class declared with the Public keyword can be accessed and invoked inside and outside the class
Private: Member variables and member functions of a class declared with the Private keyword can only be accessed and invoked within the class
Protected: Member variables and member functions of a class declared using the protected keyword can only be accessed and invoked within this class and derived subclasses.
The scope of a member of a class is only inside the class and cannot be accessed directly externally. The member functions of a class can directly access member variables and call member functions. The public member can be accessed through the class object outside the class.
In the C + + language, the default access permission for members in a struct-defined class is private for members in a class defined by Public,class.

2. C + + language struct

In the C + + language, the struct keyword has been extended, and the struct is not only a struct in the struct,c++ language of the variable set in C, but it can also be used to define member functions and to implement inheritance and polymorphism. As with structs in C, the default access level for members is public when a struct is used to define classes in the C + + language.

#include <iostream>using namespace std;struct Person{    const char* name;    int age;    virtual void print()    {        printf("My name is %s, I‘m is %d years old.\n",name,age);    }};//默认继承访问权限为publicstruct Student : Person{    void print()    {        printf("My name is %s, I‘m is %d years old."               "My score is %d\n",name,age,score);    }    void setScore(const int n)    {        score = n;    }private:    int score;};int main(int argc, char *argv[]){    Person p;    p.name = "Bob";    p.age = 30;    p.print();    Student s;    s.name = "Bauer";    s.age = 20;    s.setScore(98);    s.print();    dynamic_cast<Person*>(&s)->print();    return 0;}
3. C + + language class

Because the struct of the C + + language requires a Struct,c++ language compatible with the C language, the class is defined using the new class keyword. When you define a class by using class, the member's default access level is private.
Classes in C + + support the separation of declarations and implementations, separating the definition and implementation of a class, usually in the. h header file, only the declaration of the class, including the declaration of member variables and member functions; The implementation of the member function of the completed class in the. cpp source file.

#include <iostream>using namespace std;class Person{public:    const char* name;    int age;    virtual void print()    {        printf("My name is %s, I‘m is %d years old.\n",name,age);    }};class Student : public Person{public:    void print()    {        printf("My name is %s, I‘m is %d years old."               "My score is %d\n",name,age,score);    }    void setScore(const int n)    {        score = n;    }private:    int score;};int main(int argc, char *argv[]){    Person p;    p.name = "Bob";    p.age = 30;    p.print();    Student s;    s.name = "Bauer";    s.age = 20;    s.setScore(98);    s.print();    dynamic_cast<Person*>(&s)->print();    return 0;}
4. The difference between C + + language struct and class

The most essential differences between struct and class in the

C + + language are as follows:
A, the default access rights are different. The default access permission for a struct is public, and the class default access is private.
B, the default inherited access permissions are different. The default inherited access permission for a struct is public, and the class default inherited access is private.
C, class can be used as a keyword for defining template parameters, and structs are not. In the
C + + language, if you do not specify inherited access permissions on inheritance, the default inherited access is public or private, depending on the subclass and not the base class. Structs can inherit Class,class can also inherit a struct, the default inherited access permissions depend on whether the subclass is a struct or class, if the subclass uses a struct declaration, the default inherited access is public, if the subclass uses the class declaration, The default inherited access rights are private.

#include <iostream>using namespace std;class Person{public:    const char* name;    int age;    virtual void print()    {        printf("My name is %s, I‘m is %d years old.\n",name,age);    }};//默认继承访问权限为publicstruct Student : public Person{public:    void print()    {        printf("My name is %s, I‘m is %d years old."               "My score is %d\n",name,age,score);    }    void setScore(const int n)    {        score = n;    }private:    int score;};int main(int argc, char *argv[]){    Person p;    p.name = "Bob";    p.age = 30;    p.print();    Student s;    s.name = "Bauer";    s.age = 20;    s.setScore(98);    s.print();    dynamic_cast<Person*>(&s)->print();    return 0;}
5. C + + Language Encapsulation example

C + + class implementation stack:
Stack.h Source:

#ifndef STACK_H#define STACK_Hclass stack{public:    stack();    bool is_empty();    bool is_full();    void push(char c);    char pop();private:    char space[1024];    unsigned int top;};#endif // STACK_H

Stack.cpp Source:

#include "stack.h"#include <string.h>stack::stack(){    top = 0;    memset(space, 0, sizeof(space));}bool stack::is_empty(){    return top == 0;}bool stack::is_full(){    return top == 1024;}void stack::push(char c){    space[top++] = c;}char stack::pop(){    return space[--top];}

Main.cpp Source:

#include <iostream>#include "stack.h"#include <string.h>using namespace std;int main(){    stack st;    unsigned int i;    for(i = ‘a‘; i < ‘z‘ + 1; i++)    {        if(!st.is_full())            st.push(i);    }    for(i = ‘a‘; i < ‘z‘ + 1; i++)    {        cout<<st.pop()<<endl;    }    return 0;}

The data members in the class stack encapsulated in the C + + language are private and can be opened externally, masked by data members, and manipulated by setting access rights to data members and operation methods for externally inaccessible. C + + implements the encapsulation mechanism by defining the access level of class members. In the C + + language, classes support the separation of declarations and implementations, declare classes in a header file, and implement classes in a source file.

C + + language Learning (iii)--Encapsulation (encapsulation)

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.