[C++]——Take you to learn classes and objects

Table of contents:

After writing this article, the mountain of classes and objects is over. Keep up the good work!

1. Constructor function supplement

1.1 Constructor initialization

Insert image description here

The statement in the constructor body can only be called initial value assignment, but not initialization, because Initialization can only be initialized once, but the constructor body can be assigned multiple times. (There are three default constructors, the constructor generated by the system by default, the constructor without parameters, and the all-default constructor)

1.2 Constructor initialization list

Initialization list: Starts with a colon, followed by a comma-separated list of data members , each "member variable" is followed by an initial value or expression in parentheses.
Case:

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
//日期类
class Time
{
    
    
public:
    //初始化列表
    Time(int hour=1,int minute=1,int secnd=1)
        :_hour(hour),
        _minute(minute),
        _second(secnd)
    {
    
    }
private:
    int _hour;
    int _minute;
    int _second;
};
class Date
{
    
    
    //公有
public:
    Date(int year=1970, int month=1, int day=1)
        :_year(year),
        _month(month),
        _day(day),
        time()
    {
    
    
    }
//私有
private:
    int _year;
    int _month;
    int _day;
    Time time;
    const static size_t npos=-1;//静态变量加个const,这是一个特例,需要特殊处理,可以给缺省值,但是这个数必须是整型
};
int main()
{
    
    
    Date d;
    Date d3(2023, 11, 25);
    return 0;
}

Problems solved by the initialization list:
1——Each member variable can only appear once in the initialization list (Initialization can only be initialized once). 2 - Reference, const, custom member without default constructor, must be explicitly defined in the initialization list. , some custom type members want to be controlled by themselves, and try to use an initialization list to initialize them. The default value is equivalent to the initialization list; if a custom type member calls its default constructor, the built-in type is initialized and the value is a random value. 3——The constructor cannot only require an initialization list and no function body assignment, they can be mixed. 4——The initialization list is where member functions are defined. It is recommended that the declaration order be consistent with the initialization list to avoid understanding problems.



1.3explicit keyword

Single parameter case (supported by c++98)

#include <iostream>
using namespace std;
class Date
{
    
    
    //公有
public:
  Date(int year , int month = 1, int day = 1)
        :_year(year),
        _month(month),
        _day(day)
    {
    
    
    }
  //加上explicit关键字,禁止构造函数发生隐式转换
 /* explicit Date(int year, int month = 1, int day = 1)
      :_year(year),
      _month(month),
      _day(day)
  {
  }*/
    //私有
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    
    
    Date d1(2024);//构造函数
    //只要是类型转换就会生成临时变量,临时变量具有常属性。
    Date d2=2024;//构造函数+拷贝构造+优化——>构造函数(发生了隐式类型转化)//c++98
    return 0;
}

Multi-parameter case (c++11 support)

#include <iostream>
using namespace std;
class Date
{
    
    
    //公有
public:
    Date(int year, int month=1 , int day = 1)
        :_year(year),
        _month(month),
        _day(day)
    {
    
    
    }
    //加上explicit关键字,禁止构造函数发生隐式转换
   /* explicit Date(int year, int month = 1, int day = 1)
        :_year(year),
        _month(month),
        _day(day)
    {
    }*/
    //私有
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    
    
    Date d1(2024,2);//构造函数
    Date d2 = {
    
     2024,3 };//构造函数+拷贝构造+优化——>构造函数(发生了隐式类型转化)//c++11
    return 0;
}

Summarize:

1——For a single parameter or a constructor with default values ​​for the other parameters except the first parameter, it has the function of type conversion (forced type conversion).
2——Modifying the constructor with the explicit keyword will prohibit implicit conversion of the constructor.

2. Static members (static member variables, static member functions)

Static modified member variables do not go through the initialization list and need to be defined outside the class (declaration and definition must be separated)
Static member variable definition:

int Date::sum=0;

Static member function definition:

int Date::add()
{
    
    
//…………
}

Need to remember:
Characteristics of static modified class members:

1——Static membersare shared byall class objects, does not belong to a specific class and is stored in the static area.
2——Static member variables must be defined outside the classthis pointer 6 - Static member variables and static member functions are essentially restricted global variables and global functions. (Exclusive to this class, subject to class domain and access qualifiers) 5 - Static members are also members of the class and are affected by public, protected, and private access qualifiers. , cannot access any non-static members. hiddenNo 4——Static member function to access. Object.static member or class name::static member
3 - Class static members can use , do not add the static keyword when defining, just declare it in the class.


3. Youyuan

Friends divisionFriends functionsumfriends class.

3.1 Friend functions

Friend functions can directly access classes’ private member, which is a ordinary functiondefined outside the class > keyword needs to be added. friend, does not belong to any class, but needs to be declared inside the class. When declaring, the

Problem:
I tried to overload operator<<, but found that there was no way to overload operator<< into a member function. Because the output stream object of cout and the implicit this pointer are preempting the position of the first parameter . The this pointer defaults to the first parameter, which is the left operand. However, in actual use, cout needs to be the first formal parameter object to be used normally.
Solution:
So ​​operator<< needs to be overloaded into a global function. But it will also cause members outside the class to be unable to access. At this time, friends are needed to solve the problem. operator>>Similarly.

#include <iostream>
using namespace std;
class Date
{
    
    
    //声明友元函数
     friend ostream& operator<<(ostream& _count,Date& b);
    //公有
public:
    //初始化列表
    Date(int year,int month,int day)
        :_year(year),
        _month(month),
        _day(day)
    {
    
    }
    //私有
private:
    int _year;
    int _month;
    int _day;
};
ostream& operator<<(ostream& _count,Date& b)
{
    
    
   return  _count << b._year << "年" << b._month << "月" << b._day << "日";
}
int main()
{
    
    
    Date d(1970, 1, 1);
    cout << d ;
    return 0;
}

1——Friend function can access private and protected members of the class, but is not a class Member function
2——Friend function cannot be modified with const
3——Friend functionscan be declared anywhere in the class definition,are not restricted by class access qualifiers
4— —A function can be a friend function of multiple classes
5——The principle of calling friend functions is the same as that of ordinary functions

3.2 Friend class

Friend classAll member functions can be another class’sFriend function< /span> 3——Friend relationships cannot be inherited. If C is a friend of B and B is a friend of A, it cannot be said that C is a friend of A. 2——Friend relationships cannot be transitive. For example, the Time class and the Date class, declare the Date class as its friend class in the Time class, then you can directly access the private member variables of the Time class in the Date class, but you want to Accessing private member variables in the Date class does not work. . exchange Sex and does not have one-way 1 - The friend relationship is in another class. non-public members, can access




Notice:

Friends are a way to break through encapsulation, which will increase coupling and make it difficult to use multiple times.
High coupling: If something goes wrong, everything is wrong.
Low coupling: Even if an error occurs, some programs can still run.

4. Internal classes

Concept: **If a class is defined inside another class, this internal class is called an internal class. **The inner class is an independent class. It does not belong to the outer class, and the members of the inner class cannot be accessed through the objects of the outer class. The outer class does not have any access rights to the inner class.
Note:
The inner class is the friend class of the outer class. The inner class can access all members of the outer class through the object parameters of the outer class. But the outer class is not a friend of the inner class.

#include <iostream>
using namespace std;
class A
{
    
    
public:
    //内部类
    class B
    {
    
    
    public:
        void fun(const A& c)
        {
    
    
            cout << c.a << endl;
            cout << _a << endl;
            cout << b << endl;
        }
    private:
        int b = 3;
    };
private:
    int a=1;
    static int _a;
};
int A::_a = 2;
int main()
{
    
    
    A::B b;
    b.fun(A());//A()是匿名对象,生命周期只能在这一行
    return 0;
}

Characteristics:
1. Internal classes can be defined in public, protected, or private of external classes.
2. Note that the inner class can directly access the static members in the outer class without requiring the object or class name of the outer class.
3. sizeof (external class) = external class, has nothing to do with internal classes.

5. Anonymous objects

 A aa()//不能这样定义对象,编译器无法识别这是函数声明还是对象定义。
 //匿名对象生命周期只在这一行,下一行它就会自动调用析构函数,定义如下:
 A();
 A().Sum(1,2);

Temporary objects and anonymous objects have only one line of life cycle.

6. Compiler optimization during copy construction

During the process of passing parameters and returning values, the compiler will do some optimizations to reduce object copies.
Different compilers may have different results for these optimizations.
Implicit type: continuous construction + copy construction——>Optimized to direct construction

//先用1构造一个临时对象,在用临时对象拷贝构造aa,直接被优化成构造。
//不发生优化,拷贝一个临时变量,给它取别名。
const A& aa1=2;
A aa=1

The premise of optimization - in the same step.

Optimization method:

  1. Construction+Construction——>Construction
  2. Construction + copy construction——>Construction
  3. torture construction+torture construction——>torture construction
    Example:
    A f()
    { A aa; return aa; } A aa1=f();



7. Understand classes and objects now

For example:
How do we ask a computer to describe a washing machine

1. Users must first abstract the reality of the washing machine entity - that is, understand the washing machine at the human level of thought, what attributes the washing machine has, and what functions it has, which is a process of abstract cognition of the washing machine.
2. After 1, people already have a clear understanding of the washing machine in their minds, but the computer is not clear at this time. If you want the computer to recognize the washing machine in your imagination, you need to use some object-oriented language ( For example: C++, Java, Python, etc.) describe the washing machine using classes and input them into the computer.
3. After 2, there is a washing machine class in the computer, but the washing machine class only describes the washing machine object from the perspective of the computer. Through the washing machine class, you can instantiate a A specific washing machine object, at this time the computer can know what the washing machine is.
4. Users can use the washing machine object in the computer to simulate the actual washing machine entity.

When learning classes and objects, we must realize: A class describes a certain type of entity (object), describing what attributes and methods the object has, After the description is completed, a new custom type is formed, and specific objects can be instantiated using this custom type.

Guess you like

Origin blog.csdn.net/plj521/article/details/134537521