编程知识 cdmana.com

C + + 06 object oriented

Preface : For more information, please refer to the general outline 《 The embedded C/C++ Learning path 》

1. What is object-oriented ?

  •   Everything is object , This is the most simple way for human beings to face the world , The most natural feeling 、 Ideas and perspectives
  • Think of large-scale software as a system composed of object Composed of social
  • Object has enough intelligence , Be able to understand information from other objects , And react with appropriate behavior
  • Objects can be from high-level objects Inherit Attributes and behaviors , And allow low-level objects to Inherit Properties and behaviors, etc
  • The process of writing a program is the process of describing the properties and behavior of an object , By virtue of this ability Problem domain and Solution domain Achieve maximum unity
  • Three elements of object-oriented : encapsulation 、 Inheritance and polymorphism

2. How to object-oriented ?

  • Master at least one object-oriented Programming language , Such as C++
  • In depth understanding of encapsulation 、 Inheritance and polymorphism And other important object-oriented concepts
  • Be proficient in a kind of Metalanguage , Such as UML, Describe the design at the conceptual level .UML The class diagram is as follows
  • Study Design patterns , From the accumulation and summary of many years of successful experience
UML Class diagram

 

 3. Classes and objects

  • Have the same attribute and Behavior Objects are divided into groups , It's a class
  • Class can be used to express those that cannot directly establish a natural mapping relationship with built-in types Logic abstract
  • Class is a user-defined composite data type , That is, including the expression of attributes Member variables , It also includes expressing behavior Member functions
  • Class is a way to show the world abstract , Objects are instances of classes in the virtual world
Classes and objects

Class definition and instantiation

The general form of a class

The general form of a class

Access control qualifier

  • stay C++ in , There is no essential difference between class and structure , The only difference is : class class The default access control is private , structure struct The default access control is public .
  • The access control qualifier only works on class , Instead of acting on objects , therefore Same class Different objects of , Can access each other's non-public parts
  • Distinguish the access control attributes of different members , Embodies the C++ As an object-oriented programming language encapsulation characteristic

Access control qualifier

  A simple example , If the base class is me , The subclass is my wife and son , Outside is my colleague :

  • The public member is my name , My family, colleagues and friends know
  • Protecting members is my nickname , Only my wife and son know , Colleagues don't know
  • Private members are my private money , Only I know , Wife, son and colleagues don't know

Let's learn from a piece of code :

#include <iostream>
using namespace std;
class Student //  Create a student class 
{
public:            //  Public member access control characters 
    void who(void) //  Behavior     Member functions 
    {
        cout << " I am a " << m_name << ", This year, " << m_age << " year ." << endl;
    }
    void learn(const string &course) //  References are used to prevent duplication overhead , Add const To prevent accidental modifications 
    {
        cout << " I'm learning " << course << " Course ." << endl;
    }
    string m_name; //  Member variables 
    int m_age;
};

//  Turn student classes into objects ( Instantiation )
int main(void)
{
    Student s1 = {" Zhang San ", 22}; //  Initialize object 
    s1.who();                  //  Call member functions 
    s1.learn("C++");
    s1.m_name = " Two goods ";    //  Users can modify public member variables at will 
    s1.m_age = -100;
    s1.who();                  //  Call member functions 
}

You can see from the output , Users can Modify at will Public member variables , So there are private members , After putting the name and age into the private member , Compiling the code again will report an error : 

#include <iostream>
using namespace std;
class Student //  Create a student class 
{
public:            //  Public member access control characters 
    void who(void) //  Behavior     Member functions 
    {
        cout << " I am a " << m_name << ", This year, " << m_age << " year ." << endl;
    }
    void learn(const string &course) //  References are used to prevent duplication overhead , Add const To prevent accidental modifications 
    {
        cout << " I'm learning " << course << " Course ." << endl;
    }
private:  //  Private member control accessors 
    string m_name; //  Member variables 
    int m_age;
};

//  Turn student classes into objects ( Instantiation )
int main(void)
{
    Student s1 = {" Zhang San ", 22}; //  Initialize object 
    s1.who();                  //  Call member functions 
    s1.learn("C++");
    s1.m_name = " Two goods ";    //  Users can modify public member variables at will 
    s1.m_age = -100;
    s1.who();                  //  Call member functions 
}

 

  After putting the name into the private member , How should users name student objects ? You can create a function in a public member , When the student's name / Age satisfaction Under certain conditions When , only Create student objects . Because private member variables can be accessed inside the class .

Examples are as follows : If the user names the student ” Two goods “ Or age <=0 When , Refuse to create .

#include <iostream>
using namespace std;
class Student //  Create a student class 
{
public:            //  Public member access control characters 
    void who(void) //  Behavior     Member functions 
    {
        cout << " I am a " << m_name << ", This year, " << m_age << " year ." << endl;
    }
    void learn(const string &course) //  References are used to prevent duplication overhead , Add const To prevent accidental modifications 
    {
        cout << " I'm learning " << course << " Course ." << endl;
    }
    void setName(const string& name){
        if(name == " Two goods "){
            cout << " You're the second best !!!" << endl;
            return ;
        }
        m_name = name;
    }
    void setAge(int age){
        if(age <= 0){
            cout << " Illegal age !" << endl;
            return ;
        }
        m_age = age;
    }
private:
    string m_name; //  Member variables 
    int m_age;
};

//  Turn student classes into objects ( Instantiation )
int main(void)
{
    Student s1; //  Initialize object 
    s1.setName(" Two goods ");
    s1.setAge(-50);
    s1.who();  //  Call member functions 
    s1.setName(" Zhang Fei ");
    s1.setAge(22);
    s1.who();  //  Call member functions 
}

  You can enter the age and the name if the condition is not met ,s1 Is the object we first defined, that is Student s1;, here The name is a string ‘\0’,age It's a random number ( This is actually about code , We are not right s1 Do initialization assignment , Because when the name and age become private variables , Cannot be assigned by an equal sign , The initialization method will be described later ). below Redefinition After a reasonable name and age , Object created successfully .

Constructors

  • The function name and Class name identical , And No return type
  • When you create an object Automatically Called , Called only once
  • —— Object definition statement
  • ——new The operator
  • Assign initial values to member variables , Allocate resources , Set the The initial state
  • Object creation process
  • —— Assign... To the entire object Memory Space
  • —— Call... With construction arguments structure function -> structure Base class part -> structure member Variable -> Execution construct Code

版权声明
本文为[Goafan]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/134/202205141353266398.html

Scroll to Top