C++初阶:类与对象(初篇)

小明 2025-05-06 04:16:05 6

目录

  • 1. 类与对象
    • 1.1 引子:结构体与类
    • 1.2 什么是类(类的定义方式)
    • 1.3 类和结构体的区别
    • 1.4 类的访问限定符与封装
      • 1.4.1 访问限定符
      • 1.4.2 类的作用域与类的实例化
      • 1.5 类对象的模型
        • 1.5.1 类内部资源的存储方式
        • 1.5.3 类大小的计算方式
        • 1.6 this指针
          • 1.6.1 this指针的引入
          • 1.6.2 this���针的特性

            1. 类与对象

            1.1 引子:结构体与类

            1. 在C语言中我们学习过自定义类型结构体,其内部可以创建自定义类型的变量与内置类型的变量来满足我们的需要。
            2. 结构体的产生是为了描述简单内置类型无法定义的复杂对象。
            3. 我们知道,计算机是帮着人们解决现实世界问题的工具,将问题使用编程语言描述出来并传递给计算机来进行解决,为了更好的贴近现实生活,由此有了结构体的概念。
            4. 当我们引入面向对象的概念(C++初阶)之后,结构体已经无法满足我们的需求,为了更好的解决问题,我们引入类与对象的概念。

            1.2 什么是类(类的定义方式)

            1. 定义方式:类名(关键字Class + 类名)+ 类体(成员变量 + 类方法 + 访问限定符)
            class [这个类的名称]
            {
            public:
            	//类的成员变量
            private:
            	//类方法
            };
            
            1. 补充:C++中成员变量命名方式

              注:类的内部方法可以直接访问类的成员变量

            class Date
            {
            private:
            	int year;
            	int month;
            	int day;
            public: 
            	void Init(int year)
            	{
            		//无法正常赋值
            		year = year;
            	}
            };
            

            上述操作会导致命名冲突,编译器无法识别,发生错误,所以建议类的成员变量前都加下划线_

            ()
            class Date
            {
            private:
            	int _year;
            	int _month;
            	int _day;
            }
            
            1. 类方法的声明与定义分离
            //class.h
            class Date
            {
            private: 
            	int _year;
            	int _month;
            	int _day;
            public:
            	void Print();
            }
            //class.c
            void Date::Print()
            {
            	cout 
            	int* _data;
            	int _capacity;
            	int _top;
            };
            void StackInit(Stack* stack)
            {
            	stack-_data = NULL;
            	stack-_capacity = stack-_top = 0;
            }
            //调用方式
            struct Stack stack1;
            StackInit(&stack1);
            
            public:
            	int* _data;
            	int _capacity;
            	int _top;
            	void Print()
            	{
            		cout 
            public:
            	int _a;
            	
            	void Print();
            };
            void A::Print()
            {
            	cout 
            public:
            	int _b;
            	
            	void Print()
            	{
            		cout 
            	int _a;
            };
            cout 
            	int _a;
            	void Print()
            	{
            		cout };
            
            public:
            	int _a;
            	void Print1()
            	{
            		cout 
            		cout 
            		cout 
The End
微信