C++ class and object learning [part2: object characteristics]

C++ class and object learning [part2: object characteristics]

Constructor and destructor

Complete the initialization and cleanup of the object.
The compiler is forced to call it automatically.
Constructor syntax:

Class name(){}

Destructor syntax:

~Class name(){}

Classification and call of constructor

Classification method:

  • Classified by parameters: parameterized structure and non-parameterized structure
  • Classified by type: ordinary construction and copy construction

Three calling methods:

  • Bracketing
  • Display method
  • Implicit conversion

The specific procedures are as follows:

// arrayone.cpp -- small arrays of integers
#include <iostream>

using namespace std;

//构造函数的分类和调用
class Person
{
    
    
public: //一定要写在public权限之下
    Person()
    {
    
    
        cout << "无参构造" << endl;
    }
    Person(int a)
    {
    
    
        age = a;
        cout << "有参构造" << endl;
    }
    Person(const Person &p) //记住这种写法先,完成拷贝一份一样的进行构造
    {
    
    
        cout << "拷贝构造" << endl;
        //将传入Person身上的属性,拷贝到当前类上
        age = p.age;
    }

    ~Person()
    {
    
    
        cout << "析构" << endl;
    }

    int age;
};

int main()
{
    
    
    //括号法
    Person p1;     //默认构造函数(无参构造)
    Person p2(10); //有参构造
    Person p3(p2); //拷贝构造
    //注意事项:调用默认构造函数时,不要加(),否则就会认为是函数声明
    cout << "p2's age = " << p2.age << endl;
    cout << "p3's age = " << p3.age << endl;
    //显示法
    Person p4;
    Person p5 = Person(99);
    Person p6 = Person(p5);

    //单独一个这个,是匿名对象,当前行结束,系统立即回收匿名对象
    Person(50);
    //注意事项:不要利用拷贝构造,初始化匿名对象,编译器认为是Person(p3) === Person p3;
    
    //隐式法
    Person p7 = 10; //相当于Person p7 = person(10);(有参构造)
    Person p8 = p7; //拷贝构造
    system("pause");
    return 0;
}

Here are the different types of constructors used in different calling methods.

When to call the copy constructor

usage:

  • Initialize a new object with an already constructed object
  • Pass value to function parameter pass value
  • Return local objects by value
// arrayone.cpp -- small arrays of integers
#include <iostream>

using namespace std;

//构造函数的分类和调用
class Person
{
    
    
public:
    Person()
    {
    
    
        cout << "Person的默认构造函数调用" << endl;
    }
    Person(int age)
    {
    
    
        age_ = age;
        cout << "Person的有参构造函数调用" << endl;
    }
    Person(const Person &p)
    {
    
    
        age_ = p.age_;
        cout << "Person的拷贝构造函数调用" << endl;
    }

    ~Person()
    {
    
    
        cout << "Person的析构函数调用" << endl;
    }
    int age_;
};
//使用一个已经构建的对象初始化一个新对象
void test01()
{
    
    
    Person p1(20);
    Person p2(p2);
}
//值传递给函数参数传值
void doit(Person p)
{
    
    
}

void test02()
{
    
    
    Person p;
    doit(p);
}
//以值方式返回局部对象
Person donow()
{
    
    
    Person p1;
    return p1;
}
void test03()
{
    
    
    Person p = donow();
}

int main()
{
    
    
    //test01();
    //test02();
    test03();
    system("pause");
    return 0;
}

Here shows the timing of calling the copy constructor (call method) in different methods.
Note: The definition method of the copy constructor is special, as follows:

Person(const Person &p)
    {
    
    
        age_ = p.age_;
        cout << "Person的拷贝构造函数调用" << endl;
    }

The so-called copy construction is to copy a new class, especially to return a local object by value. What is involved is to return a new object. This object is not the ontology of p1. If you want to be the ontology of p1, what should be returned is Reference, namely:

return *this;

And, the function return type is reference, namely:

Person& (const Person &p)
    {
    
    
        age_ = p.age_;
        cout << "Person的拷贝构造函数调用" << endl;
    }

Constructor call rules

Create a class, and the C++ compiler will add at least 3 functions to each class.
Note: If a parameterized constructor is written, it will no longer be automatically constructed by default, but copy construction is still provided.
The copy construction here can be understood as automatically adding assignment statements to copy class A information to class B.
Note: If you write a copy constructor, the compiler will no longer provide other ordinary constructors.
These two notes mean that you have to write your own constructor (if you want to use it) that the compiler does not provide.

Deep copy and shallow copy

Shallow copy: simple assignment
Deep copy: re-apply for memory space in the heap area for
shallow copy problem: repeated release of the heap area memory

Initialize the list to initialize properties

Here is an initialization list to initialize the value of the attribute, the procedure is as follows:

// arrayone.cpp -- small arrays of integers
#include <iostream>

using namespace std;

//构造函数的分类和调用
class Person
{
    
    
public:
    //传统初始化操作
    // Person(int a, int b, int c)
    // {
    
    
    //     A_ = a;
    //     B_ = b;
    //     C_ = c;
    // }
    //通过初始化列表初始化属性
    Person() : A_(10), B_(20), C_(30)//不必注释该行,因为可以利用构造函数重载实现
    {
    
    
    }
    //或者
    Person(int a, int b, int c) : A_(a), B_(b), C_(c)
    {
    
    
    }

    int A_;
    int B_;
    int C_;
};
void test01()
{
    
    
    //Person p(10, 20, 30);
    // Person p;
    Person p(30, 20, 10);
    cout << "A_ = " << p.A_ << endl;
}

int main()
{
    
    
    test01();

    system("pause");
    return 0;
}

Three initialization methods are introduced here.
Among them, traditional initialization is to use parameterized constructors to initialize by passing in values.
Furthermore, the second type is list initialization, but this type of list can only be initialized to a fixed value, because it will not be repeated.
The third type of initialization is essentially the first type of upgrading and transformation, which simplifies the writing, is clear at a glance, and is very convenient.
Function overloading is used here. In this example, two constructors are reserved, and function overloading can be triggered when calling, so as to select the appropriate constructor.
(The author thought it was a mistake, and was going to comment out the last constructor, but found that the operation was correct. After that, Baidu found that there was a function overload, and I had to respect it!)

Class objects as class members

When we define a class, we can define other classes as class members. This function is demonstrated in the following code and the initialization list is added.

// arrayone.cpp -- small arrays of integers
#include <iostream>

using namespace std;

#include <string>

//类对象作为类成员
class Phone
{
    
    
public:
    Phone(string PName) : PName_(PName)
    {
    
    
        //PName_ = PName;
        cout << "Phone构造函数" << endl;
    }

    string PName_;
};

class Person
{
    
    
public:
    //相当于: Phone phone_ = PName;
    Person(string name, string PName) : name_(name), phone_(PName)
    {
    
    
        cout << "Person构造函数" << endl;
    }

    string name_;
    Phone phone_;
};
//当其他类对象作为本类成员,先构造其他类对象,再构造自身
//析构的顺序正好相反
void test01()
{
    
    
    Person p("张三", "苹果手机");

    cout << p.name_ << "拿着" << p.phone_.PName_ << endl;
}

int main()
{
    
    
    test01();

    system("pause");
    return 0;
}

In addition, it should be noted that when applying this method, other objects will be constructed first, and then itself, and the order of destruction will be exactly the opposite.
This can be understood as existing parts that can be assembled into a complete class, so the class object used is constructed first.
The results of the program are as follows:
Insert picture description here

Static member

A static member is to add the keyword static before member variables and member functions, which is called a static member.
Static members are divided into:

  • Static member variable
    • All objects share the same data
    • Allocate memory during compilation
    • In-class declaration, out-of-class initialization
  • Static member function
    • All objects share the same function
    • Static member functions can only access static member variables

I found a good article about static variables:

https://blog.csdn.net/ichliebecamb/article/details/85097922?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare

Guess you like

Origin blog.csdn.net/qq_41883714/article/details/109461896