[Elementary C++] 3. Classes and objects (process-oriented, class class, class access qualifier and encapsulation, class instantiation, class object model, this pointer)

=========================================================================

Aikanyo gitee own take

C language learning diary: keep working hard (gitee.com)

 =========================================================================

approach period:

[Basic C++] 2. Introduction to introductory knowledge
(Reference, inline function, auto keyword, range-based for loop, pointer null value nullptr) - CSDN Blog< /span>

 =========================================================================

                     

1. Preliminary understanding of process-oriented and object-oriented

C language -- Process-oriented

                    

  • C language is process-oriented and focused It is a process, analyzes the steps to solve the problem,
    Solve the problem step by step throughfunction calls

                       
  • Example:
    RequiredCompleteWashing clothes a>This itemTransmissionC languageComplete WorkDemand distribution process, as follows:
    Nabunzi  => ;  Water discharge  =>  Discharge of clothing  =>  Kindry clothes =>  Kindry clothes   =>    =>  Rewashing clothes powder =>    => 22>Refilling water  Free-washing powder

                     

                     


                    

C++ -- object-oriented

                 

  • C++ isobject-oriented, and focuses on Objects, split one thing into different objects a>Rely on interaction between objects to solve problems,

                       
  • Example
    Same methodCompleteWashing clothes a>This item, throughC++completed DemandExpression of demand for mutual demand
    Washing clothesDemand situation Yes:person,clothing , washing powder, washing machine,
    After the arrival Process:persongeneralclothing RadiantWashing machine  =>  CollapseWashing powder =>  washing machinewashing machinecleaning a>clothesclothes you can seeclean it upThroughout I have determined the alternation of the four imagescomplete,person< a i=50>Unnecessary knowledgeWashing machineSpecific is how operational
     

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

2. Introduction of classes -- struct class

                   

Clang structure structureJust ability setchange
inin C++strcut structure< a i=9>innot allowed to be fixedchange amount,not allowed to be fixed< /span>. Function

Example

BeforeIn the elementary level of data structure, the stack was implemented in C language

[Basic data structure] 5. Stack in linear table
(C language--sequence table implementation stack)_Gaogao Fatty's Blog-CSDN Blog

这rri实现的栈Stack结构体Just ability setChange amount;

And if you implement the stack in C++, you will find the Stack structure In you can also definefunction

Illustration:

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

3. Definition of class -- class class

Introduction to class class:

                  

  • In C++, can be defined using struct class, but stillprefer to define the classclass
                  
Illustration:
                            class className
                            {
                                //类体:由成员变量和成员函数组成
        
                            }; //和struct一样最后需要加上分号
  • classDefined category 关键字className Category surname,
    { } Centralcategorical subject, Note: Determined but ultimately final Undecidable omission
                  
  • The content in the class body is called the member of theclass:
    Variables in a class are called attributes of the class or member variables ;Function in class is called method of class ormember function
                 
  • When defining member variables of a class, generally add " before the name of the member variable > class means that the variable is a member variable within the ”, _
Illustration:

                     

                     


                    

Two ways to define class classes:

           

The first type: the declaration and definition of member functions are in the class body

Note:Member functionif is defined in the class , The compiler may treat it as inline function a>

Illustration:

                          

                          
---------------------------------------------------------------------------------------------

                    

The second type: the class declaration is placed in the header file, and the member function implementation is placed in the .cpp file.

  • Note:
    in .cpp text in, < /span>A certain number of functions in the specified practical category)::(action area limitersumclass namedemand communication
                     
  • Class scope:
    Class defines a New scope, All members of the classare within the scope of the class Domainin.
    When defining members outside the class, needs to use < a i=15>:: Scope operatorspecifies which class scope the member belongs to
Illustration:

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

4. Class access qualifiers and encapsulation

Access qualifier:

                          

  • C++realisticpackagingmethod:对对对加较性,让method of giving symbolic attributes in one placegeneralclass
    use

    PassAccess(PassAccess Qualifier< /span>Selectively provide its interface to external users)Management permissions

                        

There are three access qualifiers:

  • public (public), protected()Privateprivate), protection(
                    
  • public (publicly owned): publicly modified AdultinoutsideJapaneseinsideDirect access to the city
                   
  • protectedprotection)和  privatevisible questioninsideonly available Directly accessible question,Employee of the recipient):Private(

Note:

currentlyvisiting the areathis area,this area个访问频频率类similar
Currently
current level,allowableprotected privateis a separate section,
after< /span>
Division of talents, knowledge, and pathsConfirmationUnderstood

                          

                          
---------------------------------------------------------------------------------------------

                    

Access permission scope:

  • The access scopestartswhere the access qualifier appearsuntil The next access qualifier appears until,
    If no access qualifier appears later< /span> the end of the class, that is, until } reaches , then the scope of
                         
  • classtargetaccess limitprivate a>,structpropertypublic struct-required C language)
Note:

The access qualifier is only usefulat compile time, When the data is mapped to memory, there is no difference in access qualifiersA

                  

Illustration:

                          

                          
---------------------------------------------------------------------------------------------

                    

The difference between struct and class in C++:

C++ needs to be compatible with C language, so struct in C++In addition to being used as class, can also be used as Structure uses. The class defined by struct and the class defined by class Difference:

Class defined by structThe default access permissionispublic, class defined classThe default access permissionisprivate a>

Note:

inherits and at template parameter list position , < There is also a difference between /span>, Learn more about it laterclass and struct

                     

                     


                    

Package:

                  

  • Front viewExistenceThree major characteristics:Encapsulation< /span>Specific sealing characteristicsMajor research objectives, classical education stage Present. multiple, continuation,

                     
  • enclosure:
    generalnumber positionsum operational fixed function(method) progressorganic combination隐藏conceptual attributesumActual details
    External public openingAlternating arrival and departure
                  
  • The essence of encapsulation is a kind of management, allowing users Can use classes more conveniently, for example:
    for computers Such acomplex device,provided to users Only one power button,
    input through keyboard, etc.Hardware componentsmemory, graphics card, CPU is actually what the computer really works But to complete daily tasks. proceed Interactcomputers and usersLet , etc., USB jack, monitor,

                           
  • Forcomputer users,don’t have to worry about internal core components,
    For example, how the circuits on the motherboard are laid out , CPU How the interior is designedetc.
    Users only need to know ,
    how to turn on , How to interact with the computer through keyboard and mouseJust.
    Therefore, computer manufacturers put a case on the outside of the factory < /span>keyboard jack< /span> just allows users to interact with the computeretc., and mouse, Provide external power switch only , internal implementation details, hides

                      
  • To implement encapsulation inC++ language,
    can Convert data and through classes Functions for operating data(Methods)Organically combined , hides object internal implementation via access permissions The details,control which functions can be called directly outside the class

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

5. Instantiation of classes

  • The process of creating an object using class type is calledInstantiation of class
                  
  • Class is a descriptionobject >design drawings needed when building a houseThe : For example. No actual memory space is allocated to store it and defines only one class, Limits which members a class has, model is the same as a’s design drawing can be regarded as a class , Throughdesign drawingscandesign and build multiple similar houses< /span>occupy physical space and store datacan actually instantiated Objects, is just a designclass Similarly,, but there is no physical building existenceOnly design what is neededdesign drawings, design drawing classCan be regarded as multiple objects of the There are many similar houses here,







                     
  • A class can instantiatemultiple objects,The instantiated object , occupies actual physical space ,
    storage Class member variables, but does not store Class member functions ,
    Becausemultiple objects of the same class call The same member function, so themember function will be stored in Public code area
Illustration:

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

6. Class object model

Calculate the size of a class object:

               

Class can have both member variables and There can bemember functions,

SoWhat does an object of a class contain? How to calculate the size of a class?

            

How class objects are stored:

  • one piececategorymedium possiblenumber of staff members,< /span>,former functionsomeone

    Butactuallyclass objects only have classes Member variables, and have no member functions,

    Because member functions can be shared by multiple class objects, so member function is stored in public code area< /span>,

    Andthe member variables of each class object areindependentof

                     
  • So the size of a class object, is actually The sum of "member variables" in this class< a i=9>,
    When calculating its size, needs to use the same method as calculating the size of the structure a>:Memory alignment
                
  • If in , < /span>empty class object one byte to uniquely identify the object of this empty class gave the The compiler , calculating the size of the empty class will be special , empty class, the class is called has no member variables classa
Illustration:

                     

                     


                    

Structure memory alignment rules:

            

calculationclass(conception) Size and small Understanding the demandInheritance knowledgeknowledge,
关于内existent对齐Previously available customer details details

The Thirtieth Day of Learning C [Custom Types: Structure, Enumeration, Union]_Gaogao Fatty’s Blog-CSDN Blog

                  

A brief review of memory alignment:

  • The first member is at the address and the structure offset is 0
                    
  • The amount of staff requiredRequired informationA certain number(Integer number) /span>8对齐数默认in the middleVS (Two people in the middlethe size of the class typegivenThe number of pieces of equipment you need to read =


                      
  • The total size of the structure is:An integer multiple of the maximum number of alignmentsMaximum number of alignments = The largest of all variable types and Default alignment parameterThe smaller of the two

                   
  • If it isnestedstructure , Nested structure aligned to its own maximum alignment number At integer multiples, the overall size of the structure is allAn integer multiple)Number of alignments including nested structures(Maximum number of alignments

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

7. this pointer

Introduction of this pointer:

              

First define a date class Date:
//日期类Date:
class Date
{
public:    
    void Init(int year, int month, int day)
    {
        _year = year;
        _month = month;
        _day = day;
    }

    void Print()
    {
        cout << _year << "_" << _month << "_" << _day << endl;
    }
    
private:
    int _year;
    int _month;
    int _day;
}

//主函数:
int main()
{
    Date d1;
    Date d2;

    d1.Init(2023, 10, 7);
    d2.Init(2022, 10, 7);

    d1.Print();
    d2.Print();

    return 0;
}
  • For the above class, there is such a question:

    Date classin Init given Print ,Function field with a different representational division, Constructive functionTwo parts

    ThatWhen the d1 object calls the Init member function,
    the function is< a i=4>How to know that d1 object should be set, instead of What about d2 object?
                   

  • C++ solves this problem by introducing this pointer Question, i.e.: C++ compiler for each Non-static member functionAdded oneHidden this pointer parameter, letthe pointer point to transparent to users are It’s just that all operations through this pointer. accessed are all and The operations "Member variables"All in the function body),The object that calls the function when the function is running (The current object,that is, users do not need to pass it themselves,< /span>Compiler automatic completion



                    

Characteristics of this pointer:

  • this pointer'stype:class type*< /span> Cannot assign value to this pointer, member function, , that is, in the const
               
  • only availableformer function< /span>Internal use
                  
  • this pointer is essentiallymember function”< /span>actual parameterthe this pointer is not stored in the objectSo. is passed to this formal parameter as object address uses , object calls the member function, when the formal parameter's

                       
  • this pointer is "member function"first Hidden pointer parameters,
    Generally, the compiler a> does not Requires user to pass, automaticallyecx registerpassed
                      
  • this fingertipthis oneform referencethis one< /span>)mediumecx parasitic organexistence releasethis finger piecemiddle,VS editingTop surface栈帧Existence release,Local change
Illustration:

                     

                     


                    

Comparison of C language and C++ implementation classes:

            

C language implementation class (type):

When C language implements a type (structure), the operation functions related to the type have the following common features:
  • eachcorresponding operation functiontofirst numberTo be attacheditem type(construct body) changeable finger,
    cometakeorder type< /span>bottom layer structuretarget
                          
  • In the function must be correctthe first parameter ("Underlying structure") Detection, < a i=9>Because this parameter may be NULL
                      
  • The function passesthe first parameter(“Underlying structure< a i=4>”)tooperate this type(structure< /span>)
                 
  • When calling a function this type must be passed ( structure)Address of variable
                        

In the structure can only define the structure to store data, Methods for operating data cannot be placed in the structure,

ImmediateNumerical systemSumOperation numerical systemCorrect< /span>,actually the meeting will be completed, andtargetseparation

Involvesa large number of pointer operations, may make mistakes if you are not careful

                          

                          
---------------------------------------------------------------------------------------------

                    

C++ implementation class:

C++ MediumTransmissionKey general Number of positions a> From here on operational deferential function (method )Complete progression,

Throughaccess permissions you can also control whether those methods can be called outside the class, encapsulation, that is,

When used, it is like using one's own members, which is more in line with people's understanding of a matter.

andeachmember function(member method< /span>”),Underlying structure (" first parameter in C language does not need to be passed like the )

CompilerAfter compilationthis parameterwill be restored automatically ( through hidden this pointer),

That is, the "underlying structure" of in C++< /span>C languageneeds to be maintained by the userThen, and are maintained by the compilerParameters

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

Code related to this blog:

​​​​​Stack.h -- Header file:

#pragma once

//类头文件:

class Stack
{
private: //这是访问修饰符下一标题处会了解到
	//成员变量:
	int* a;
	int top;
	int capacity;

public: //同样是访问修饰符
	//成员函数:
	void Init(); //栈初始化函数(方法)-- 声明

	void Push(int x); //出栈函数(方法)-- 声明

	/*
	* 成员函数可以分文件实现,
	* 也可以直接就在头文件中实现,
	* 但这样的直接在类中实现函数的话,
	* 该函数会被默认为是内联函数(inline),
	* (虽然是内联函数,但编译器确定是否展开)
	* 
	*		所以正确的用法是:
	* 长函数的声明和定义要分离(分文件实现),
	* 短函数可以直接在类中就进行声明
	*/
	bool Empty()
	{
		return top = 0;
	}
};

                     

                     


                    

Stack.cpp -- C++ file

#define _CRT_SECURE_NO_WARNINGS 1

//包含类头文件:
#include "Stack.h"

//类函数(方法)实现文件:

/*
* 通过命名空间(类名)和作用域限定符,
* 来指定实现类中对应的函数(方法)
* (类定义的也是一个域)
*/

//栈初始化函数(方法)-- 实现
void Stack::Init() 
//指定实现Stack类中的Init函数(方法)
{
	a = 0;
	top = 0;
	capacity = 0;

	//a、top、capacity都是栈的成员变量
}

//出栈函数(方法)-- 实现
void Stack::Push(int x) 
//指定实现Stack类中的Push函数(方法)
{
	//…… 
}

                     

                     


                    

Test.cpp -- C++ file

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <iostream>
using namespace std;

//使用C++实现一个栈:

//C语言中实现栈:
//struct Stack
//{
//	int* a;
//	int top;
//	int capacity;
//};
//
C语言中栈相应的函数:
//void StackInit(struct Stack* ps);
//void StackPush(struct Stack* ps, int x);
//……

/*
* 由此可见:C语言中栈的数据和方法是分离的
* 数据 -- struct Stack
* 方法 -- StackInit、StackPush等等
*		(C语言 -- 面向过程)
* 
* C++中:兼容C语言struct的所有用法,
* 不仅兼容,而且还将struct升级成了“类”
*/

//C++中实现栈:
//struct Stack
//{
//	int* a;
//	int top;
//	int capacity;
//
//	/*
//	* 2、类中可以定义与该类相关的函数(方法)
//	* 
//	* (1)不需要像C语言中将数据和函数(方法)分离。
//	* 
//	* (2)因为函数(方法)被包含在类中,
//	* 所以不再需要像C语言中必须将函数定义在全局中,
//	* 所以函数名不需要定义得像 StackInit(堆的初始化函数)一样,
//	* 来特指是谁的初始化函数,直接在类中定义为 Init 即可,
//	* 该 Init函数 在Stack(堆)类的域中,
//	* 就是只属于Stack的Init函数
//	*/
//
//	void Init()
//	{
//		a = 0;
//		top = 0;
//		capacity = 0;
//	}
//
//	void Push(int x)
//	{
//		//……
//	}
//
//};


//int main()
//{
//	//C语言中调用struct“类型”:
//	struct Stack s1;
//
//	//C++中调用struct“类”:
//	Stack s2; 
//	/*
//	* 1、类名就是类型,Stack就是类型,不需要加struct
//	* struct后的名称就是类名,要调用类,直接调用类名即可,
//	* 不用加struct
//	*/
//	
//	//C++中:
//	//调用类中的变量或者函数的方法
//	//和调用结构体成员的方法一样:
//	s2.Init(); //调用栈类中的Init函数 (C++)
//
//	//调用栈类中的出栈Push函数(C++):
//	s2.Push(1);
//	s2.Push(2);
//	s2.Push(3);
//	s2.Push(4);
//
//	//C语言中:
//	struct Stack s1; 
//	//声明时还需加struct(不加typedef)的话
//
//	//调用的是全局中的函数:
//	StackInit(&s1);
//	StackPush(&s1, 1);
//	StackPush(&s1, 2);
//	StackPush(&s1, 3);
//	
//	return 0;
//}

//假设定义一个链表结点类:
struct ListNode
{
	ListNode* next; 
	/*
	* 这里可以直接使用类名类型来定义变量了,
	* 而不是C语言中的:struct ListNode* next; 
	*/
	
	int val;
};


//class Date
//{
//public:
//	void Init(int year, int month, int day)
//	{
//		_year = year;
//		_month = month;
//		_day = day;
//	}
//private:
//	/*
//	* C++中一般会在成员变量前加一个 “_” ,
//	* 表示该变量为类内部的成员变量,
//	* 防止在成员函数调用时和形参命名冲突
//	*/
//	
//	int _year;
//	int _month;
//	int _day;
//
//};

//int main()
//{
//	Date d; 
//	
//	d.Init(2023, 10, 17);
//
//	return 0;
//}



/*
* C++中,虽然可以使用struct定义类,
* 但还是更喜欢通过class来定义类,
* 
* class中由两部分构成:
* 变量(成员变量)和函数(成员函数),
* 两者统称类的成员
* 
* 类会通过访问限定符来实现封装,
* 访问限定符分为:
* public(共有)、protected(保护)、private(私有)
* 
* public(共有):类中和类外都可以进行访问
* protected(保护):类中可以访问,类外不能访问
* private(私有):类中可以访问,类外不能访问
* 
* 在当前阶段,可以认为protected和private是没有区别的,
* 等后面了解了继承才能够知道两者的区别
* 
*			struct 和 class 的区别:
* 1、class的默认访问权限为private,但实践中建议还是明确写上限定符
*	 struct默认访问权限为public(为了兼容C语言)
* 2、(其它就没有什么大的区别)
* 
*			C++中设置访问限定符的目的:
* C语言中没有访问限定符的概念,数据和方法是分离的,
* 有时实现一个目标可以通过数据完成,也可以通过方法完成,
* 程序员素养比较高的话应该是使用方法(函数)完成,这是比较规范的
* 
* 所以C++中类的成员默认是private私有的,无法在外部调用数据,
* 在解决一个问题时就只能通过在类中定义方法(函数)来完成,
* 提高代码的规范性
*/

//class Stack
//{
//private: 
//	//私有:让以下三个成员变量的权限为私有
//	int* a;
//	int top;
//	int capacity;
//
//public:
//	//共有:让以下的两个成员函数的权限为共有
//	void Init()
//	{
//		a = 0;
//		top = 0;
//		capacity = 0;
//	}
//
//	void Push(int x)
//	{
//		//……	
//	}
//
//	bool Empty()
//	{
//		return top == 0;
//	}
//
///*
//* 一个访问限定符的作用范围为:
//* 如果后面还有限定符 -- 当前限定符到下个限定符
//* 如果后面没有限定符 -- 当前限定符到 “}” 
//*/
//};

//int main()
//{
//	Stack s1;
//	 
//	//权限为共有的成员可以在类外部进行调用:
//	s1.Init(); //Init函数为共有
//	s1.Push(1); //Push函数为共有
//	s1.Push(2);
//	s1.Push(3);
//	s1.Push(4);
//
//	//权限为私有或保护的成员不可以在类外部进行调用:
//	s1.a = 0; //成员变量a为私有
//}


//类的实例化:

//C++中 “{}” 定义的都是域

//class Date
//{
//public:
//	void Init(int year, int month, int day)
//	{
//		_year = year;
//		_month = month;
//		_day = day;
//	}
//
//private:
//	int _year;
//	int _month;
//	int _day;
//	//这里这些成员变量只是声明,还没有开辟空间
//	/*
//	* 变量是否定义(实现)要看是否有开辟空间
//	* (在内存中开辟空间)
//	*/
//};

/*
* 类 和 对象  -->  一对多的关系
* 一个类可以有多个对象,可以想象类是设计图,
* 对象是通过设计图建出来的房子,一个设计图
* 可以设计建出多个类似的房子
*/


//class A
//{
//private:
//	char _ch;
//	int _a;
//}; //内存对齐问题


class B
{}; 
//没有成员变量的类(空类)的大小:1
/*
* 没有成员变量的类,说明该类不需要存储数据,
* 虽然该类没有成员变量,但还是可以创建该类的对象,
* 为了要表示一个空类的对象,证明空类B的对象存在,
* 就需要为这个空类对象开一个字节大小的空间,
* 这个字节不存储有效数据,仅标识定义的对象存在过
*/


class C
{
public:
	void f()
	{};
};
//有成员函数没有成员变量的类的大小:1
/*
* 该类还是没有成员变量,所以本质还是一个空类,
* 虽然有成员函数,但成员函数并不存放在该类中,
* 而是存储在公共代码区中,所以该类大小为1个字节
*/



//int main()
//{
//	Date d1; //定义(实例化)一个对象
//	Date d2; //再定义(实例化)一个对象
//	Date d3; //再再定义(实例化)一个对象
//
//	/*
//	* 定义一个对象后,对象中的成员变量
//	* 作为对象一部分,一起开辟了空间,
//	* 这时成员变量才被定义(实现)了
//	*/
//
//	d1.Init(2023, 10, 7);
//	d2.Init(2022, 10, 7);
//	/*
//	* (同个类)不同对象的成员函数是一样的:
//	* 这里d1和d2调用的是同一个函数
//	*(汇编指令call调用的是同一函数地址)
//	*/
//
//	//假设将成员变量的权限设置为public:
//	d1._year++;
//	d2._year++;
//	/*
//	* (同个类)不同对象的的成员变量是不一样的:
//	* 这里 d1的_year 和 d2的_year 不是同一个
//	*/
//
//	return 0;
//}


//int main()
//{
//	Date d1; //定义(实例化)一个对象
//	Date d2; //再定义(实例化)一个对象
//	Date d3; //再再定义(实例化)一个对象
//
//	//使用sizeof计算类的大小:
//	cout << sizeof(d1) << endl; //8个字节
//	/*
//	* sizeof计算类对象的大小和
//	* sizeof计算结构体大小是一样的,
//	* 所以要考虑内存对齐
//	* 
//	* sizeof计算类对象的大小时,
//	* 只会计算成员变量的大小,再考虑内存对齐,
//	* 不会考虑成员函数的大小
//	* 
//	* 成员函数不在对象里面,因为同一个类的不同对象
//	* 调用的是同一个成员函数(同名函数的情况下),
//	*(汇编指令call调用的是同一函数地址)
//	* 但同一个类的不同对象各自的成员变量是独立的,
//	* 类对象d1中的成员变量 和 类对象d2中的成员变量
//	* 是不同的,所以sizeof计算类对象时计算的是其成员变量
//	* 
//	* 成员变量存在对象中,而成员函数不存在对象中的原因:
//	* 成员变量各个对象不同(独立),
//	* 但成员函数调用的都是同一个,
//	* 所以没必要在所有对象中都存成员函数的地址,
//	* 将其放在一个公共的区域(公共代码区)是更适合的,
//	* 公共代码区在编译完成后是一堆指令,
//	* 编译链接时就可以确定函数的地址
//	*/
//	cout << sizeof(A) << endl;  //A类大小:8个字节
//	cout << sizeof(B) << endl;  //B类大小:1个字节
//	cout << sizeof(C) << endl;  //C类大小:1个字节
//
//	return 0;
//}


class Date
{
public:
	//Date类初始化函数:
	void Init(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	//Data类打印日期函数:
	void Print()
	{
		cout << _year << "_" << _month << "_" << _day << endl;
	}
		/*
		* d1 和 d2 都调用该成员函数,但结果却不同的原因:
		* 
		* 我们写的 void Print()函数,编译器编译时实际上是这样的:
		* void Print(Date* const this),有一个隐藏的参数--this指针
		* (所有我们定义的成员函数都默认有一个this指针参数)
		* 
		* d1调用函数时,访问的是: &d1->_year、&d1->month、&d1->_day
		* 此时 this指针 就是 d1的指针 ,&d1是实参,Date* this是形参
		* 访问的是d1对象的_year、_month、_day
		* 
		* d2调用函数时,访问的是: &d2->_year、&d2->month、&d2->_day
		* 此时 this指针 就是 d2的指针 ,&d2是实参,Date* this是形参
		* 访问的是d2对象的_year、_month、_day
		* 
		* this指针是形参,是个局部变量,是存放在栈帧上面的
		* (VS编译器中,this指针被存放在ecx寄存器中)
		*/
	//编译器编译时的Print函数:
	void Print(Date* const this)
	{
		cout << this->_year << "_" << this->_month << "_" << this->_day << endl;
		/*
		* 注:不能显式写出this相关实参和形参,但可以在成员函数中显式写上this指针
		*(之后有地方会需要显式地在成员函数中写出this指针)
		*/
	}

private:
	int _year;
	int _month;
	int _day;

};

class A
{
private:
	char _ch;
	int _a;
};

int main()
{
	Date d1; //定义(实例化)一个对象
	Date d2; //再定义(实例化)一个对象

	d1.Init(2023, 10, 7);
	d2.Init(2022, 10, 7);

	d1.Print();
	d2.Print();
	
	//编译器编译时的426和427代码:
	d1.Print(&d1); //传送“this”指针
	d2.Print(&d2); //传送“this”指针

	return 0;
}


//对象用 “.” 访问成员;指针用 “->” 访问成员


/*
*				1、
* C语言数据和函数(方法)是分离的,
* 而C++通过类将数据(成员变量)和成员函数(成员方法)绑定在一起
* 
*				2、
* C语言调用函数时,需要将类型变量传给函数,
* 而C++因为有this指针的存在,不需要传类对象给成员函数
*/

Guess you like

Origin blog.csdn.net/weixin_63176266/article/details/134354146