C++: Classes and Objects (Part 1): Class & Structure Concepts, Access Qualifiers, Object Instantiation, Class Object Model

Table of contents

1. Understand process-oriented and object-oriented

1.1 Process-oriented

1.2 Object Oriented

2. Preliminary understanding of classes and structures

2.1 Structure (struct)

2.2 Classes

Three, class

3.1 Grammar

3.2 Definition method

3.2.1 Write regardless of file

3.2.2 Writing by file (commonly used)

4. Class access qualifiers and encapsulation

4.1 Access Qualifiers

4.2 Packaging

5. Instantiation of the class

Six, the object model of the class

6.1 How to calculate the object size of a class instance

6.2 Guessing the storage method of class objects

6.3.1 The object contains each member of the class (variable + function)

6.3.2 Only one copy of the code is saved, and the address of the code is saved in the object

6.3.3 Only member variables are saved, and member functions are stored in public code segments


1. Understand process-oriented and object-oriented

Process-oriented (Procedural Programming) and object-oriented (Object-Oriented Programming) are two different programming paradigms . They have significant differences in programming ideas, structures and implementation methods.

1.1 Process-oriented

Procedure-oriented is a procedure-based (or function) programming style . In procedure-oriented programming, the execution flow of a program is realized by sequentially executing a series of functions or procedures. Data and functions are separated, that is, data and functions that manipulate data are separated. A program is broken down into subtasks, and each subtask is completed by one or more functions. The procedure-oriented programming style is suitable for simple, linear problems, but as the complexity of the problem increases, the program may become difficult to maintain and expand.

Features:

  • Programs are made up of functions, and functions are the core concept .
  • Data and functions are separated .
  • Good for simple, linear problems.
  • Programming thinking is more top-down .

Example:

#include <stdio.h>

// 函数:计算矩形的面积
float calculateArea(float length, float width) {
    return length * width;
}

// 函数:计算矩形的周长
float calculatePerimeter(float length, float width) {
    return 2 * (length + width);
}

int main() {
    float length = 5;
    float width = 3;
    float area = calculateArea(length, width);
    float perimeter = calculatePerimeter(length, width);

    printf("矩形的面积:%.2f\n", area);
    printf("矩形的周长:%.2f\n", perimeter);

    return 0;
}

1.2 Object Oriented

Object-oriented is an object-centric programming style . In object-oriented programming, data and functions (called methods) that manipulate the data are encapsulated together to form objects. An object is an instance of a class, and a class is an abstraction of an object. The properties (data) and methods (behavior) of the object are defined through the class, and subclasses can be derived through the inheritance mechanism to achieve code reuse and scalability. Object-oriented programming style is more flexible and modular, suitable for dealing with complex problems.

Features:

  • Programs are made up of objects, and objects are the core concept .
  • The data and the methods for manipulating the data are encapsulated together.
  • Suitable for dealing with complex, multi-level problems.
  • Programming thinking is more bottom-up .

Example:

#include <iostream>

class Rectangle {
public:
    // 构造函数
    Rectangle(float length, float width) {
        this->length = length;
        this->width = width;
    }

    // 方法:计算矩形的面积
    float calculateArea() {
        return length * width;
    }

    // 方法:计算矩形的周长
    float calculatePerimeter() {
        return 2 * (length + width);
    }

private:
    float length;
    float width;
};

int main() {
    float length = 5;
    float width = 3;

    // 创建Rectangle对象
    Rectangle rectangle(length, width);

    // 计算面积和周长
    float area = rectangle.calculateArea();
    float perimeter = rectangle.calculatePerimeter();

    std::cout << "矩形的面积:" << area << std::endl;
    std::cout << "矩形的周长:" << perimeter << std::endl;

    return 0;
}

In the procedural example, we used functions to perform the calculations, while in the object-oriented example, we created a Rectangleclass called , which encapsulates the data (length and width) and the associated methods (calculating area and perimeter). The object-oriented programming of C++ makes the code more modular and extensible, suitable for dealing with complex problems.

2. Preliminary understanding of classes and structures

2.1 Structure (struct)

Features:

  • Structures are a data type in C and are supported by many other programming languages ​​as well.
  • A structure can contain multiple member variables (fields) of different types, and these fields are stored sequentially in memory .
  • A structure has no member functions (methods), only data members.
  • By default, the members of the structure are public (public), and all code can directly access the members of the structure.
  • Structs cannot inherit from other structs or types.
  • The definition of a structure is similar to the definition of a variable, using keywords struct.

Example:

#include <stdio.h>

// 定义矩形结构体
struct Rectangle {
    float length; // 矩形的长度
    float width;  // 矩形的宽度
};

int main() {
    // 创建Rectangle结构体变量
    struct Rectangle rect;

    // 初始化矩形的长度和宽度
    rect.length = 5.0;
    rect.width = 3.0;

    // 计算矩形的面积和周长
    float area = rect.length * rect.width;
    float perimeter = 2 * (rect.length + rect.width);

    return 0;
}

2.2 Classes

Features:

  1. A class is a concept in object-oriented programming (such as C++) used to create custom data types .
  2. Classes can contain data members (properties) and member functions (methods), encapsulating data and methods for manipulating data .
  3. Classes can implement access control, and define the accessibility of members through keywords public, privateand .protected
  4. Classes support the inheritance mechanism, and subclasses can be derived to achieve code reuse and scalability.
  5. A class is an abstraction of an object, and an object is an instantiation of a class . When you create an object using a class, the object occupies memory and contains the member variables and member functions in the class definition.

Example:

#include <iostream>

// 定义矩形类
class Rectangle {
public:
    float length; // 矩形的长度
    float width;  // 矩形的宽度

    // 计算矩形的面积
    float calculateArea() {
        return length * width;
    }

    // 计算矩形的周长
    float calculatePerimeter() {
        return 2 * (length + width);
    }
};

int main() {
    // 创建Rectangle对象
    Rectangle rect;

    // 初始化矩形的长度和宽度
    rect.length = 5.0;
    rect.width = 3.0;

    // 计算矩形的面积和周长
    float area = rect.calculateArea();
    float perimeter = rect.calculatePerimeter();

    return 0;
}

remind:

In C++, struct and class have the same function, struct can be used as a keyword of a class, define data and functions in the structure for encapsulation, and access qualifiers can also be used , but in C++, it is more inclined to use class to define classes . At the same time, the data inside the structure defined by the struct keyword in the C language is public by default , and the variables defined through the structure can be directly accessed, which is equivalent to the public permission in the C++ class. The data and functions in the C++ class are private by default . It cannot be accessed outside the class, and three access qualifiers are used according to the actual situation.

Note: There are also differences between struct and class in the position of inheritance and template parameter list, which will be introduced later.

Three, class

3.1 Grammar

class className
{
    // 类体:由成员函数和成员变量组成
};  // 一定要注意后面的分号

class is the keyword to define the class, className is the name of the class , {} is the body of the class , note that the semicolon after the end of the class definition. The contents of the class body are called members of the class: the variables in the class are called member attributes or member variables ; the functions in the class are called member methods or member functions .

3.2 Definition method

3.2.1 Write regardless of file

#ifndef RECTANGLE_H
#define RECTANGLE_H

// 定义矩形类
class Rectangle {
public:
    // 构造函数:初始化矩形的长度和宽度
    Rectangle(float length, float width);

    // 成员函数:计算矩形的面积
    float calculateArea();

    // 成员函数:计算矩形的周长
    float calculatePerimeter();

private:
    float length; // 矩形的长度
    float width;  // 矩形的宽度
};

#endif



This code is only used for functional demonstration. Readers who encounter unfamiliar concepts and syntax will be explained in subsequent articles.
It should be noted that if a member function is defined in a class, the compiler may treat it as an inline function.

3.2.2 Writing by file (commonly used)

Rectangle.h (header file)

#ifndef RECTANGLE_H
#define RECTANGLE_H

// 定义矩形类
class Rectangle {
public:
    // 构造函数:初始化矩形的长度和宽度
    Rectangle(float length, float width);

    // 成员函数:计算矩形的面积
    float calculateArea();

    // 成员函数:计算矩形的周长
    float calculatePerimeter();

private:
    float length; // 矩形的长度
    float width;  // 矩形的宽度
};

#endif

Rectangle.cpp (implementation file)

#include "Rectangle.h"

// 构造函数的实现
Rectangle::Rectangle(float length, float width) {
    this->length = length;
    this->width = width;
}

// 成员函数:计算矩形的面积
float Rectangle::calculateArea() {
    return length * width;
}

// 成员函数:计算矩形的周长
float Rectangle::calculatePerimeter() {
    return 2 * (length + width);
}

Note: The class name:: needs to be added before the member function name , indicating that the function definition belongs to this class.

4. Class access qualifiers and encapsulation

4.1 Access Qualifiers

The way of C++ to achieve encapsulation: use classes to combine the properties and methods of the object to make the object more complete, and selectively provide its interface to external users through access rights.

In C++, class access qualifiers are used to control the visibility and access rights of members of the class (member variables and member functions) to the outside . There are three types of access qualifiers for a class: public, , privateand protected. These access qualifiers determine where members of a class can be accessed.

1. public

  • public is the default access qualifier, if no access qualifier is specified, the default is public.
  • Public members can be accessed from outside the class as well as from inside the class.

2. private:

  • Private members can only be accessed inside the class, not directly outside the class.
  • Private members are used to hide implementation details, hide data inside the class, and prevent direct access and modification by external code.

3. protected

  • Protected members are similar to private members and can only be accessed inside the class.
  • But protected members are visible to derived classes (subclasses) , allowing derived classes to access protected members of the base class .

illustrate:

  • The scope of access rights starts from the position where the access qualifier appears until the next access qualifier appears. If there is no access qualifier behind, the scope ends at }, which is the end of the class.
  • Access qualifiers are only useful at compile time, when the data is mapped to memory, there is no difference in access qualifiers.

4.2 Packaging

Encapsulation is an important feature of object-oriented programming, which allows classes to encapsulate data and operations on data to form an independent entity. Encapsulation protects data security by setting data members as private, and implements access and modification of data through public member functions. In this way, external code can only access and manipulate data through the public interface, and cannot directly access private members, thus hiding the implementation details and making the internal structure and data of the class invisible to external code .

Package advantages:

  • Data hiding and security: The private members of the class are invisible to external codes, avoiding direct access and modification of data, and protecting the security of data.
  • Simplified interface: Public member functions provide an interface for the class to interact with the outside world, hiding internal implementation details, making the code using the class more concise and easy to read.
  • Code reuse: The interface of a class can be reused by other code, which improves the maintainability and reusability of the code.

5. Instantiation of the class

In object-oriented programming, class instantiation refers to the process of creating an object through a class . A class defines a custom data type, and the instantiation of a class is to use this data type to create a concrete entity, also known as an object . Through instantiation, we can use the member functions and member variables of the class to manipulate the data and behavior of the object.

For example. Instantiating an object from a class is like building a house using architectural design drawings in reality. Classes are like design drawings, only what is needed is designed, but there is no physical building . The object can actually store data and occupy the actual physical space .

Example:

class Person{
    //类定义
}

int main(){
    //实例化出对象p
    Person p;
}

Six, the object model of the class

6.1 How to calculate the object size of a class instance

class Person{
private:
    int _count;

public:
    void print(){
        cout << "Hello World" << endl;
    }
};

A class can have both member variables and member functions, so what does an object of a class contain? How to calculate the size of a class? It is worth our deep thinking! We should think about how classes are stored!

6.2  Guessing the storage method of class objects

6.3.1 The object contains each member of the class (variable + function)

Thinking: The member variables inside each object are different, but the function is the same as the function we usually use, and only needs to have a code. If stored in this way, a function code is stored in each object , It will cause a waste of space, and a little thinking can also think that this method will not work! !

6.3.2 Only one copy of the code is saved, and the address of the code is saved in the object

 Compared with the first method, this method naturally saves a lot of space, so let us simply verify it in a specific environment!

 It can be seen that only int variables are stored in the instantiated object, and there is no so-called pointer. Look at the third!

6.3.3  Only member variables are saved, and member functions are stored in public code segments

The class object model stores member variables in the memory of the object, and member functions are usually stored in the public code segment (also called code area, code segment, or text segment). This design helps save memory space, because member functions are shared between different object instances, instead of saving a copy for each object.

When you call a member function of a class, you are actually accessing the function code in the public code segment through the object pointer. The specific calling process is as follows:

  1. Create a class object: Create a new object instance through the class constructor, including the memory of the member variables.

  2. Using a pointer to an object: To call a member function of an object, you need to use a pointer to that object.

  3. Access member functions: Access member functions of objects through pointers. Use the arrow operator (->) to access member functions of the object pointed to by the pointer.

#include <iostream>

class MyClass {
public:
    int myVar;

    void nonVirtualFunction() {
        std::cout << "This is a non-virtual function" << std::endl;
    }

    virtual void virtualFunction() {
        std::cout << "This is a virtual function" << std::endl;
    }
};

int main() {
    MyClass obj1;
    MyClass obj2;

    obj1.nonVirtualFunction(); // 调用非虚函数
    obj1.virtualFunction(); // 调用虚函数

    MyClass* ptr = &obj2;
    ptr->nonVirtualFunction(); // 使用指针调用非虚函数
    ptr->virtualFunction(); // 使用指针调用虚函数

    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_57082854/article/details/132110531