C++—Classes and Objects

Everything we study can be called an object. Objects have state, operations and behavior. Usually a value is used to describe the state of the object. Object operations are used to change the state of the object. Objects and operations on objects are behaviors of objects.

An abstraction of objects with the same or similar properties is a class. Classes have properties and operations. Data structures are usually used to describe the attributes of a class. The properties of a class are an abstraction of the state of the object. Describe the operation of the class with the user name and the method to implement the operation. Class operations are an abstraction of object behavior.

Class 1

The form of defining a class in C++ is

class 类的名字
{
    
    
	public:
		公有的数据成员定义
		公有的成员函数
	private:
		私有的数据成员定义
		私有的成员函数
};

A class is composed of two parts: a class header and a class body. The class header is class + class name. The class body is what is enclosed in curly braces. The class body generally consists of two parts

  • data member
    specifies the internal representation of an object of the class
  • Member function
    specifies the operation of the class

Members of a class have three different access rights

  • Public
    members can be accessed outside the class
  • Private
    members can only be accessed by member functions within the class
  • Protected
    members can only be accessed by member functions of the class or member functions of derived classes

Data members are usually private. Member functions are usually partly public and partly private. Public member functions can be accessed outside the class, also known as the class interface .

类的成员函数通常在类外定义。The general form of a member function of a class defined outside the class is as follows

返回类型 类名::函数名(输入参数)

在类外定义的成员函数,仍然需要在类内声明。

2 objects

A class is a user-defined data type that does not occupy a memory unit. Classes exist in static programs (that is, programs before running), while dynamic object-oriented programs (that is, programs that are running) are composed of objects. The execution of the program is realized by sending messages between objects, and the objects are instances of the class (accounting for memory units).

2.1 Creating objects

Objects are similar to variables. Objects created outside of all functions are called global objects . Objects created within a function are called local objects . Global objects and local objects have the same lifetime as global variables and local variables. Objects created through the new operation are called dynamic objects . Dynamic objects need to be undone with the delete operation.

The following comes from C knowing that
new and delete are keywords for dynamic memory allocation and release. new can create an object of a specified type and return a pointer to the object; delete can release a specified object and return the memory occupied by the object to the system. These two keywords are often used to create and delete objects. When using new and delete, you need to pay attention to the problems of memory leaks and pointer hanging. At the same time, when using new to dynamically allocate memory, it is also necessary to ensure that the allocated memory space will not exceed the system limit, otherwise the memory application will fail. Therefore, careful consideration is required when using new and delete to ensure that the program can run correctly.

int* p = new int(5);
delete p;

2.2 Operation of objects

For an object created, it needs to be operated by calling the member functions defined in the object class. The general form of the operand is

对象名.成员函数名(实参表)

or

指向对象的指针->成员函数名(实参表)

Here is a simple example to show the operation of the object

#include<iostream>

using namespace std;

class temp
{
    
    
    public:
    	int a;   // 数据成员
    	
        // 成员函数
        void function1 ()
        {
    
    
            cout << "function1 is called!" << endl;
        }
        // 类外定义的成员函数的声明
        void function2 ();
};

// 类外成员函数
void temp::function2 ()
{
    
    
    cout << "function2 is called!" << endl;
}

int main()
{
    
    
    temp i;   // 创建一个temp类的局部对象
    temp* p;
    p = new temp;   // 创建一个temp类的动态对象,用p指向该对象
    
    // 调用成员函数对创建的对象进行操作
    i.function1();
    // 调用成员函数对创建的对象进行操作
    p->function2();
    delete p;
    
    return 0;
}

The output is

function1 is called!
function2 is called!

2.3 Constructor

Every object created while the program is running can only be used after it has been initialized. A special initialization function is defined in C++, called a constructor . The constructor is called automatically when the object is created. The name of the constructor is the same as the class name, and it has no return type and return value. When an object is created, the constructor is automatically called for initialization. 当未定义构造函数,但是编译器需要嗲用构造函数时,编译器会自动生成默认的构造函数来初始化对象。Therefore, not all classes need constructors. Here is a simple example

#include<iostream>

using namespace std;

class temp
{
    
    
    public:
    	int a;   // 数据成员
    	
        // 构造函数
        temp ()
        {
    
    
            a = 10;
        }
        // 成员函数
        void function1 ()
        {
    
    
            cout << a << endl;
        }
};

int main()
{
    
    
    temp i;   // 创建一个temp类的局部对象
    
    // 调用成员函数对创建的对象进行操作
    i.function1();
    
    return 0;
}

The output is 10. If no constructor is defined, the output is 0.需要注意的是,对构造函数的调用是对象创建过程的一部分,对象创建之后就不能再调用构造函数了。

2.4 Destructors

When the object is destroyed, the destructor is automatically called to do some cleanup. The destructor also has the same name as the class, but there is a "~" before the name, and the destructor also has no return type and return value. The destructor takes no parameters and cannot be overloaded. 析构函数的调用顺序与构造函数的调用顺序相反。Let's understand with a simple example

#include<iostream>

using namespace std;

class temp
{
    
    
    
    public:
        // 构造函数
        temp ()
        {
    
    
            cout << "构造函数被调用" << endl;
        }
        // 析构函数
        ~temp()
        {
    
    
            cout << "析构函数被调用" << endl;
        }
};

int main()
{
    
    
    temp i,j;   // 创建temp类的局部对象
    cout << "main函数" << endl;
    
    return 0;
}

The output is

output result

3 static members

The method of defining static members is relatively simple, just add a "static" before the member variables and member functions. Static members have the following characteristics

  • Static members are shared by all objects of the class . It will not be created and initialized multiple times as the object is created.
  • Static functions can only access static data members .
  • Static member variables can only be initialized outside the class .
  • Public static members can be called and accessed through "class name::member function (input parameter)/member variable" .
#include<iostream>

using namespace std;

class temp
{
    
    
    public:
        int a;   // 数据成员
        
        // 构造函数
        temp ()
        {
    
    
            a = 10;
        }
};

int main()
{
    
    
    // 通过对象访问成员变量
    temp i;   // 定义一个temp类的对象
    
    cout << "a=" << i.a << endl;
    
    return 0;
}

如果a是静态成员,还可以通过“类名::成员变量名”访问成员变量。

#include<iostream>

using namespace std;

class temp
{
    
    
    public:
        static int a;   // 数据成员
};

// 静态变量只能在类外进行初始化
int temp::a = 10;

int main()
{
    
    
    // 通过对象访问成员变量
    temp i;   // 定义一个temp类的对象
    
    cout << "a=" << i.a << endl;
    
    // 通过类名访问成员变量
    cout << "a=" << temp::a << endl;
    
    return 0;
}

4 this pointer

Before introducing the this pointer, let's look at a simple example

#include<iostream>

using namespace std;

class temp
{
    
    
    public:
        void function (int m)
        {
    
    
            a = m;
            cout << "a=" << a << endl;
        }
    
    private:
        int a;
        int b;
};

int main()
{
    
    
    temp i;   // 定义一个类temp的对象
    
    i.function(1);
    
    return 0;
}

The output is

a=1

Now consider a question, for the class function function, how does it know which object to operate on? This requires the this pointer to tell it.

  • The this pointer points to the current object and can access all member variables of the current object. Including private, protected, public.
  • The this pointer is a const pointer and cannot be assigned or modified.
  • The this pointer is only defined in the non-static member functions of the class, and is only accessed in the member functions of the class.

In fact, the above function can be written as

void function (temp* const this,int m)
{
    
    
	this -> a = m;
}

5 Tomomoto

In order to protect data in C++, private access control is used to restrict access to data members in the class outside the class. In C++, you can specify a global function , some other class, or a member function of some other class to directly access the private (private) and protected (protected) members of another class, which are called friend functions and friend classes respectively. And friend class functions , commonly known as friends . The role of friends is to improve the flexibility of program design, and it is a compromise between data protection and data access efficiency.

Guess you like

Origin blog.csdn.net/qq_45217381/article/details/131700210