C++ notes - the first class and object

Table of contents

introduce

The difference between C and C++

 The connection and difference between C++ and Java

The difference between C++ and Python

1. First acquaintance with the class

1. In C++, not only variables can be defined in the structure, but also functions can be defined

 2. Class definition

There are two ways to define a class:

3. Class access qualifiers and encapsulation

3.1 Access Qualifiers

What is the difference between struct and class in C++?

3.2 Packaging

4. Class scope

5. Instantiation of the class

6. Class object model 

6.1 How to calculate the size of a class object

6.2 Storage method of class objects 

6.3 Structure memory alignment rules

7. this pointer 

7.1 What is this pointer

7.2 Characteristics of this pointer

Can this pointer be null?

Second, the member functions of the class

The 6 default member functions of the class:

1. Constructor

 2. Destructor

2.1 Features

3. Copy constructor

3.1 Concept

3.2 Features

4. Assignment operator overloading 

4.1 Operator overloading

 4.2 Assignment operator overloading

5. const member

Member functions of const modified classes

6. Address and const address operator overloading

3. In-depth contact with constructors

1. Constructor body assignment

2. Initialization list

3. The explicit keyword

Four, static members

1. Concept

2. Features

Five, C++11 member initialization 

Six, fate? Youyuan!

1. Friend function

 2 friend class

Seven, inner class

Concept and Features


introduce

C++ is object-oriented.


The difference between C and C++

C is a process-oriented language, and C++ is a superset of the C language, adding object-oriented features, that is, encapsulation, inheritance, and polymorphism. Encapsulation can hide the implementation details of the code, making the code modular and easier to manage and expand. Inheritance enables subclasses to reuse the code and properties of the parent class. Polymorphism is to implement the same interface by rewriting the virtual function of the parent class by subclasses, resulting in different behaviors.

C and C++ manage memory in different ways. C++ mainly uses new and delete. In addition, C++ also adds concepts such as function overloading and reference.

 The connection and difference between C++ and Java

Both C++ and Java are object-oriented languages. C++ needs to be compiled into an executable file to run. Java is compiled and run on the jvm virtual machine. Therefore, Java has better cross-platform features, but its execution efficiency is not as good as C++.

The memory of C++ needs to be manually managed by the programmer, while Java can be completed by a virtual machine, using the mark-recycling algorithm.

C++ has pointers, Java does not, and Java only has references.

Both Java and C++ have constructors, C++ has destructors, and Java does not.

The difference between C++ and Python

Python is a scripting language for interpretation and execution, and C++ is a compiled language, so Python's cross-platform is better than C++.

Python uses indentation to distinguish different code blocks, and C++ uses curly braces.

C++ needs to define the type of the variable first, but Python does not.

There are more Python libraries than C++, and it is more convenient to use.



1. First acquaintance with the class



1. In C++, not only variables can be defined in the structure, but also functions can be defined

struct Student
{
    void SetStudentInfo(const char* name, const char* gender, int age)
    {
        strcpy(_name, name);
        strcpy(_gender, gender);
        _age = age;
    }

    void PrintStudentInfo()
    {
        cout<<_name<<" "<<_gender<<" "<<_age<<endl;
    }

    char _name[20];
    char _gender[3];
    int _age;
};

 transfer:

int main()
{
    Student s;
    s.SetStudentInfo("哈哈", "女", 18);
    return 0;
}

 2. Class definition

class className
{
    // 类体:由成员函数和成员变量组成
}; //分号

The elements in the class are called the members of the class: the data in the class are called the attributes or member variables of the class; the functions in the class are called the methods or member functions of the class.

There are two ways to define a class:

1. The declaration and definition are all placed in the class body. It should be noted that if the member function is defined in the class, the compiler may treat it as an inline function

 2. The declaration is placed in the .h file, and the class definition is placed in the .cpp file (the second method is better)

//person.h
class Person
{
public:
	void show()
	{
		cout << _name << " " << _age << endl;
	}
public:
	char* _name;
	int _age;

};
//person.cpp
#include "person.h"
void Person::show()
{
	cout << _name << " " << _age << endl;
}

3. Class access qualifiers and encapsulation

3.1 Access Qualifiers

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

Access qualifiers:

protected、private、public

[Description of access qualifiers]
1. Members modified by public can be directly accessed outside the class


2. Protected and private modified members cannot be directly accessed outside the class (here protected and private are similar)


3. The scope of access rights starts from the occurrence of the access qualifier until the next occurrence of the access qualifier


4. The default access permission of class is private, and struct is public (because struct is compatible with C)

Access qualifiers are only useful at compile time, when the data is mapped to memory, there is no difference in access qualifiers

What is the difference between struct and class in C++?

Answer: C++ needs to be compatible with C language, so struct in C++ can be used as a structure. In addition, struct in C++ can also be used to define classes.
It is the same as class is to define a class, the difference is that the default access mode of members of struct is public, and the default access mode of members of class is private.

3.2 Packaging

The three major characteristics of object-oriented: encapsulation, inheritance, and polymorphism.

Encapsulation: hide the properties and implementation details of the object, and only expose the interface to interact with the object


4. Class scope

A class defines a new scope, and all members of the class are in the scope of the class. To define members outside the class, you need to use the :: scope parser to indicate which class domain the member belongs to

class Person
{
public:
	void show()
	{
		cout << _name << " " << _age << endl;
	}
public:
	char* _name;
	int _age;

};

void Person::show()
{
	cout << _name << " " << _age << endl;
}

5. Instantiation of the class

The process of creating an object with a class type is called instantiation of the class

1. Define a class without allocating actual memory space to store it


2. A class can instantiate multiple objects, and the instantiated objects occupy the actual physical space to store class member variables

For example, many figures can be made based on a paper man, and each figure may have differences due to the manufacturer's problems.  


6. Class object model 

6.1 How to calculate the size of a class object

There are member variables stored in the object, but no member functions. Each object has independent member variables


Calculate the size of a class or class object: only look at member variables, and the memory alignment rules are consistent with the structure

Empty class: 1 byte. In order to distinguish different empty classes, the empty class can also instantiate objects, and the address of each object is different, so the compiler will implicitly add a byte to the empty class.

6.2 Storage method of class objects 

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

class A1 {
public:
	void f1() {}
private:
	int _a;
};

// 类中仅有成员函数
class A2 {
public:
	void f2() {}
};

// 类中什么都没有---空类
class A3
{};

//sizeof(A1) : __4____ sizeof(A2) : __1____ sizeof(A3) : ___1___

 The size of a class is actually the sum of the "member variables" in the class. Of course, memory alignment is also required. Pay attention to the size of the empty class. The empty class is special. The compiler gives the empty class a byte to uniquely identify the class

6.3 Structure memory alignment rules

+ The offset of the first member in the structure is 0
+ Other member variables should be stored according to the address of an integer multiple of the alignment number
+ Alignment number = min (the default alignment number of the compiler, the alignment number of this member), in Linux it is 4. In vs, it is 8
+ the total size of the structure is an integer multiple of the maximum alignment number

+ If a structure is nested, the nested structure is aligned to an integer multiple of its own maximum alignment, and the overall size of the structure is an integer multiple of all maximum alignments (including the alignment of the nested structure) .


7. this pointer 

7.1 What is this pointer

Only non-static class member function objects have this pointer, and this pointer can only be used in member functions of the class, and it points to the object where the member function is called.

Hidden this pointer: When calling a member function, the actual parameter cannot be passed to this. When defining a member function, you cannot explicitly declare the formal parameter to this. Inside a member function, you can write out.

class Date
{
public:
	void Display()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
		//cout<< this->_year << this->_month << this->_day <<endl;  
	}
	void SetDate(int year, int month, int day)
	{
		_year = year;
		//this->_year = year;
		_month = month;
		_day = day;
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};
int main()
{
	Date d1, d2;
	d1.SetDate(2018, 5, 1);
	d2.SetDate(2018, 7, 1);


	d1.Display();
	d2.Display();
	//void Display(Date * this) 形参
	//{}

	return 0;
}

The C++ compiler adds a hidden pointer parameter to each "non-static member function", so that the pointer points to the current object (the object that calls the function when the function is running), and the operation of all member variables in the function body is Go through that pointer to ask. It's just that all operations are transparent to the user, that is, the user does not need to pass it, and the compiler completes it automatically.

7.2 Characteristics of this pointer


1. The type of this pointer: class type * const 2. It can only be used inside the
" member function " 3. The this pointer is actually a formal parameter of
a member function in essence , when the object calls the member function , the object address is used as the actual parameter passed to the this parameter. So the this pointer is not stored in the object . 4. The this pointer is the first implicit pointer parameter of the member function . Generally, it is automatically passed by the compiler through the ecx register and does not need to be passed by the user. Since it is a formal parameter, it is generally stored on the stack.

Can this pointer be null?

class A
{
public:
	void PrintA()
	{
		cout << _a << endl;
	}
	void Show()
	{
		cout << "Show()" << endl;
	}
private:
	int _a;
};
int main()
{
	A* p = nullptr;//空指针不是语法错误,编译不会报错

	p->PrintA();//运行到这里时,崩溃,因为此时 调用 _a,this->_a
	//把p这个空指针作为实参赋给this,对空指针解引用。

	p->Show();
}

The member function does not exist in the object, and p calls the member function page without a null pointer.



Second, the member functions of the class



The 6 default member functions of the class:

Initialization and cleanup: constructor, destructor

Copy assignment: copy construction, assignment operator overloading

Take address overload: take address for ordinary objects and const objects


1. Constructor

The constructor is a special member function with the same name as the class name, which is automatically called by the compiler when creating a class type object, to ensure that each data member has a suitable initial value, and is called only once in the life cycle of the object .

The main task is to initialize objects.
Its characteristics are as follows:
1. The function name is the same as the class name.


2. No return value.


3. The compiler automatically calls the corresponding constructor when the object is instantiated.


4. The constructor can be overloaded.

5. If no constructor is explicitly defined in the class, the C++ compiler will automatically generate a default constructor without parameters. Once it is explicitly defined, the compiler will no longer generate it.

6. Both the parameterless constructor and the default constructor are called default constructors, and there can only be one default constructor.

Note: No-argument constructors, full default constructors, and constructors generated by the compiler by default can all be considered default member functions

7. The default constructor generated by the compiler will call its default member function for the custom type member

class Date
{

public:
	// 1.无参构造函数
	Date()
	{}
	// 2.带参构造函数
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
private:
	int _year;
	int _month;
	int _day;
};
void TestDate()
{
	Date d1; // 调用无参构造函数
	Date d2(2015, 1, 1); // 调用带参的构造函数
	// 注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明
	// 以下代码的函数:声明了d3函数,该函数无参,返回一个日期类型的对象
	Date d3();
}

 2. Destructor

The destructor is automatically called when the object is destroyed

2.1 Features

Destructors are special member functions.
Its characteristics are as follows:
1. The name of the destructor is to add characters   
before the class name 2. No parameters and no return value.
3. A class has one and only one destructor. If not explicitly defined, the system will automatically generate a default destructor.
4. When the object life cycle ends, the C++ compilation system automatically calls the destructor

5. The default destructor generated by the compiler calls its destructor for custom type members

typedef int DataType;
class SeqList
{
public:
	~SeqList()
	{
		if (_pData)
		{
			free(_pData); // 释放堆上的空间
			_pData = NULL; // 将指针置为空
			_capacity = 0;
			_size = 0;
		}
	}
private:
	int* _pData;
	size_t _size;
	size_t _capacity;
};


3. Copy constructor


3.1 Concept

Creates a new object identical to an object. An object that already exists, to copy and initialize an object that will be instantiated immediately

3.2 Features

The copy constructor is also a special member function, and its characteristics are as follows:
1. The copy constructor is an overloaded form of the constructor.
2. The copy constructor has only one parameter and must be passed by reference , and the method of passing by value will cause infinite recursive calls.

class Date
{

public:
	// 1.无参构造函数
	Date()
	{}
	// 2.带参构造函数
	Date(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}

    //3.拷贝构造函数
	Date(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}


private:
	int _year;
	int _month;
	int _day;
};

int main()
{
    Date d1;
    Date d2(d1);//调用拷贝构造函数
    return 0;
}

 3. If no definition is displayed, the system generates a default copy constructor. The default copy constructor object is stored in memory and copied in byte order. This kind of copy is called shallow copy, or value copy

 4. The difference between shallow copy and deep copy will be discussed later, precisely because of this difference. We need to implement our own copy construction


4. Assignment operator overloading 

4.1 Operator overloading

The function name is: the keyword operator followed by the operator symbol that needs to be overloaded.
Function prototype: return value type operator operator (parameter list)

1. An overloaded operator must have an operand of class type or enumeration type.

2. The meaning of the operator used for built-in types cannot be changed, for example: the built-in integer + cannot change its meaning
3. When an overloaded function is used as a class member, its formal parameters seem to be 1 member function less than the number of operands 4.
The operator has a default formal parameter this, which is limited to the first formal parameter
5.       .*, ::, sizeof, ?:, .    Note that the above five operators cannot be overloaded

bool operator==(const Date& d1, const Date& d2)
{
    return d1._year == d2._year;
        && d1._month == d2._month
        && d1._day == d2._day;
}

//bool operator==(Date* this, const Date& d2)
// 这里需要注意的是,左操作数是this指向的调用函数的对象
bool operator==(const Date& d2)
{
	
	bool operator==(Date* const this, const Date & d)
	{
		return _year == d2._year;
		    && _month == d2._month
			&& _day == d2._day;
	}
	
}

 4.2 Assignment operator overloading

Date& operator=(const Date& d)
{
    if(this != &d)
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
}

1. Parameter type
2. Return value
3. Check whether you assign a value to yourself
4. Return *this
5. If a class does not explicitly define an assignment operator overload, the compiler will also generate one to complete the value copy of the object in byte order .

6. Sometimes you still have to write an assignment copy yourself

int main()
{
    Date d1;
    Date d2(2018,10, 1);

// 这里d1调用的编译器生成operator=完成拷贝,d2和d1的值也是一样的。
    d1 = d2;

return 0;
}

5. const member

Member functions of const modified classes

The const-decorated class member function is called a const member function. The const-modified class member function actually modifies the implicit this pointer of the member function , indicating that any member of the class cannot be modified in the member function.


6. Address and const address operator overloading

Just use the default one, and you can reload it yourself when you want others to get the specified content

class Date
{
public:
	Date* operator&()
	{
		return this;
	}
	const Date* operator&()const
	{
		return this;
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};


3. In-depth contact with constructors



1. Constructor body assignment

The statement in the body of the constructor can only be called initial value assignment, not initialization. Because the initialization can only be initialized once, and the constructor body can be assigned multiple times.


2. Initialization list

A colon, followed by a comma-separated list of data members, each "member variable" followed by an
initial value or expression enclosed in parentheses.

class Date
{
public:
    Date(int year, int month, int day)
    : _year(year)
    , _month(month)
    , _day(day)
    {}
private:
    int _year;
    int _month;
    int _day;
};

Each member variable can only appear once in the initialization list (initialization can only be initialized once)


The class contains the following members, which must be placed in the initialization list for initialization:
reference member variable
const member variable
custom type member (this class has no default constructor

class B
{
public:
    B(int a, int ref)
    :_aobj(a)
    ,_ref(ref)
    ,_n(10)

private:
    A _aobj; // 没有默认构造函数
    int& _ref; // 引用
    const int _n; // const
};

Try to use initialization list initialization, because whether you use initialization list or not, for custom type member variables, it must be initialized with initialization list first.

The order in which member variables are declared in a class is the order in which they are initialized in the initialization list

 Notice:

It makes no difference whether a built-in type uses an initializer list or not.

A custom type uses an initializer list: its own constructor is called.

Not used: The default constructor will be called first, then its own constructor, and then assigned.


3. The explicit keyword


Constructors can not only construct and initialize objects, but also have type conversion functions for single-parameter constructors

Modifying the constructor with explicit will prohibit the implicit conversion of the single-argument constructor

class Date
{
public:
	Date(int year)
		:_year(year)
	{}
	explicit Date(int year)
		:_year(year)
	{}
private:
	int _year;
	int _month;
	int _day;
};
void TestDate()
{
	Date d1(2018);

	// 用一个整形变量给日期类型对象赋值
	
	d1 = 2019;
}


Four, static members

1. Concept

Class members declared static are called static members of the class, member variables modified with static are called static member variables; member functions modified with static are called static member functions. Static member variables must be initialized outside the class

class A
{
public:
	A() { ++_scount; }
	A(const A& t) { ++_scount; }
	static int GetACount() { return _scount; }
private:
	static int _scount;
};

int A::_scount = 0;//初始化

void TestA()
{
	cout << A::GetACount() << endl;
	A a1, a2;
	A a3(a1);
	cout << A::GetACount() << endl;
}

2. Features

1. Static members are shared by all class objects and do not belong to a specific instance
2. Static member variables must be defined outside the class without adding the static keyword
3. Class static members can be used class name::static member or Object. Static members to access
4. Static member functions do not have a hidden this pointer, and cannot access any non-static members
5. Like ordinary members of a class, static members also have three access levels: public, protected, and private, and can also have a return value



Five, C++11 member initialization 

private:
// Non-static member variables can be given a default value when the member is declared.
int a = 10;



Six, fate? Youyuan!

Friends are divided into: friend function and friend class
, but friends will increase the degree of coupling and destroy the encapsulation, so friends should not be used more often.

1. Friend function

Friend functions can access private and protected members of a class, but not member functions of the class

Friend functions cannot be modified with const


Friend functions can be declared anywhere in the class definition, not restricted by class access qualifiers


A function can be a friend function of multiple classes


The calling of friend functions is the same as that of ordinary functions 


 2 friend class


All member functions of a friend class can be friend functions of another class, and can access non-public members of another class.


The friendship relationship is one-way and not exchangeable.


Friendship cannot be passed
 

class Date;
class Time
{

friend class Date; // 声明日期类为时间类的友元类,则在Date类中就直接访问Time类中的私有成
员变量

};


Seven, inner class

Concept and Features


concept :

If a class is defined inside another class, the inner class is called an inner class. Note that this inner class is an independent class at this time, it does not belong to the outer class, let alone call the inner class through the object of the outer class. The outer class does not have any privileged access to the inner class
Note: The inner class is the friend class of the outer class. Pay attention to the definition of the friend 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.

characteristic:

1. The inner class can be defined as public, protected, or private in the outer class.
2. Note that the inner class can directly access the static and enumeration members in the outer class, without the object/class name of the outer class.
3. sizeof (external class) = external class, has nothing to do with the inner class



Guess you like

Origin blog.csdn.net/MuqiuWhite/article/details/129493553