C++ classes - constructors and destructors

Constructors and destructors of C++ classes

class constructor

The constructor of a class is a special member function of the class that is executed every time a new object of the class is created.

The name of the constructor is exactly the same as the name of the class, and the constructor can be used to set initial values ​​for certain member variables. The constructor does not need to specify a return value type, because no type will be returned, and void will not be returned.

for example:

#include <iostream>
using namespace std;

class Line
{
    
    
    public:
        int length;
        Line(int len){
    
    
            // 这是构造函数
            length=len;
        }
};
// 程序的主函数
int main( )
{
    
    
    Line line(6);// 设置长度
    cout << "Line的length:" << line.length <<endl;
    return 0;
}

Use an initializer list to initialize fields

Use an initialization list to initialize fields, taking the above Line as an example:

Line(int len):length(len) {
    
    
    ...
}

The above code is equivalent to the following:

Line(int len){
    
    
    length=len;
}

Suppose there is a class C with multiple fields x, y, z, etc. that need to be initialized. Similarly, you can use the above syntax and just use commas to separate different fields, as shown below:

C::C( double a, double b, double c): x(a), y(b), z(c)
{
    
    
    ...
}

class destructor

The destructor of a class is a special member function of a class that is executed every time a created object is deleted.

The name of the destructor is exactly the same as the name of the class, except that it is prefixed with a tilde (~). It does not return any value and cannot take any parameters. Destructors help release resources before exiting the program (such as closing files, releasing memory, etc.).

for example:

#include <iostream>
using namespace std;

class Line
{
    
    
    public:
        int length;
        Line(int len){
    
    
            // 这是构造函数
            length=len;
        }
        ~Line(void){
    
    
            // 这是析构函数
            cout<<"该对象已经被销毁"<<endl;
        }
};
// 程序的主函数
int main( )
{
    
    
    Line line(6);// 设置长度
    cout << "Line的length:" << line.length <<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_61316509/article/details/131694317