主页:醋溜马桶圈-CSDN博客

专栏:c++_醋溜马桶圈的博客-CSDN博客

gitee:mnxcc (mnxcc) - Gitee.com

目录

1.面向过程和面向对象初步认识

面向过程(C语言)

面向对象(C++)

2.类的引入和定义

2.1 类的引入

2.2 类的定义

类的两种定义方式:

成员变量命名规则的建议:

3. 类的访问限定符及封装/作用域和实例化

3.1 访问限定符

【访问限定符说明】

C++中struct和class的区别

3.2 封装

3.3 类的作用域

3.4 类的实例化 

4.类对象模型 

4.1 如何计算类对象的大小

4.2 类对象的存储方式猜测

4.3 结构体内存对齐规则

5.this指针 

5.1 this指针的引出

5.2 this指针的特性

6.构造函数和析构函数

6.1 类的6个默认成员函数

6.2 构造函数

6.2.1 概念

6.2.2 特性

6.3 析构函数  

6.3.1 概念

6.3.2 特性

7.拷贝构造函数 

7.1 概念

7.2 特征

8.友元

8.1 友元函数

8.2 友元类

9.内部类和匿名对象 

9.1 内部类

1.概念

2.特性

9.2 匿名对象 

9.3 拷贝对象时的一些编译器优化 

10.定位new表达式(placement-new) 

使用格式:

使用场景:

11.日期类的实现-Class Date 

 代码实现

测试截图 


1.面向过程和面向对象初步认识

面向过程(C语言)

C语言是面向过程的,关注的是过程,分析出求解问题的步骤,通过函数调用逐步解决问题

面向对象(C++)

C++是基于面向对象的,关注的是对象,将一件事情拆分成不同的对象,靠对象之间的交互完成

2.类的引入和定义

2.1 类的引入

C语言结构体中只能定义变量,在C++中,结构体内不仅可以定义变量,也可以定义函数。比如:之前在数据结构初阶中,用C语言方式实现的栈,结构体中只能定义变量;现在以C++方式实现,会发现struct中也可以定义函数

#include<iostream>
#include<string>
using namespace std;
typedef int DataType;
struct Stack
{
	void Init(size_t capacity)
	{
		_array = (DataType*)malloc(sizeof(DataType) * capacity);
		if (nullptr == _array)
		{
			perror("malloc申请空间失败");
			return;
		}
		_capacity = capacity;
		_size = 0;
	}
	void Push(const DataType& data)
	{
		// 扩容
		_array[_size] = data;
		++_size;
	}
	DataType Top()
	{
		return _array[_size - 1];
	}
	void Destroy()
	{
		if (_array)
		{
			free(_array);
			_array = nullptr;
			_capacity = 0;
			_size = 0;
		}
	}
	DataType* _array;
	size_t _capacity;
	size_t _size;
};
int main()
{
	Stack s;
	s.Init(10);
	s.Push(1);
	s.Push(2);
	s.Push(3);
	cout << s.Top() << endl;
	s.Destroy();
	return 0;
}

上面结构体的定义,在C++中更喜欢用class来代替

2.2 类的定义

class className
{
// 类体:由成员函数和成员变量组成
};  // 一定要注意后面的分号

class为定义类的关键字,ClassName为类的名字,{}中为类的主体,注意类定义结束时后面号不能省略

类体中内容称为类的成员:类中的变量称为类的属性成员变量; 类中的函数称为类的方法或者成员函数

类的两种定义方式:

  1. 声明和定义全部放在类体中,需注意:成员函数如果在类中定义,编译器可能会将其当成内联函数处理
  2. 类声明放在.h文件中,成员函数定义放在.cpp文件中,注意:成员函数名前需要加类名::

一般情况下,更期望采用第二种方式

成员变量命名规则的建议:

我们看看这个函数,是不是很僵硬?

这里的year到底是成员变量,还是函数形参?

class Date
{
public:
    void Init(int year)
    {
        // 这里的year到底是成员变量,还是函数形参?
        year = year;
    }
private:
    int year;
};

所以一般都建议这样

class Date
{
public:
    void Init(int year)
    {
        _year = year;
    }
private:
    int _year;
};

或者这样

class Date
{
public:
    void Init(int year)
    {
        mYear = year;
    }
private:
    int mYear;
};

3. 类的访问限定符及封装/作用域和实例化

3.1 访问限定符

C++实现封装的方式:用类将对象的属性与方法结合在一块,让对象更加完善,通过访问权限选择性的将其接口提供给外部的用户使用

【访问限定符说明】

  1. public修饰的成员在类外可以直接被访问
  2. protected和private修饰的成员在类外不能直接被访问(此处protected和private是类似的)
  3. 访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时为止
  4. 如果后面没有访问限定符,作用域就到 } 即类结束。
  5. class的默认访问权限为private,struct为public(因为struct要兼容C)

注意:访问限定符只在编译时有用,当数据映射到内存后,没有任何访问限定符上的区别

C++中struct和class的区别

问题:C++中struct和class的区别是什么?

解答:C++需要兼容C语言,所以C++中struct可以当成结构体使用。另外C++中struct还可以用来定义类。和class定义类是一样的,区别是struct定义的类默认访问权限是public,class定义的类默认访问权限是private。注意:在继承和模板参数列表位置,struct和class也有区别

3.2 封装

面向对象的三大特性:封装、继承、多态

在类和对象阶段,主要是研究类的封装特性,那什么是封装呢?

封装:将数据和操作数据的方法进行有机结合,隐藏对象的属性和实现细节,仅对外公开接口来和对象进行交互。

封装本质上是一种管理,让用户更方便使用类

比如:对于电脑这样一个复杂的设备,提供给用户的就只有开关机键、通过键盘输入,显示器,USB插孔等,让用户和计算机进行交互,完成日常事务。但实际上电脑真正工作的却是CPU、显卡、内存等一些硬件元件

对于计算机使用者而言,不用关心内部核心部件,比如主板上线路是如何布局的,CPU内部是如何设计的等,用户只需要知道,怎么开机、怎么通过键盘和鼠标与计算机进行交互即可。因此算机厂商在出厂时,在外部套上壳子,将内部实现细节隐藏起来,仅仅对外提供开关机、鼠标以及键盘插孔等,让用户可以与计算机进行交互即可

在C++语言中实现封装,可以通过类将数据以及操作数据的方法进行有机结合,通过访问权限来隐藏对象内部实现细节,控制哪些方法可以在类外部直接被使用

3.3 类的作用域

类定义了一个新的作用域,类的所有成员都在类的作用域中在类体外定义成员时,需要使用::作用域操作符指明成员属于哪个类域

class Person
{
public:
    void PrintPersonInfo();
private:
    char _name[20];
    char _gender[3];
    int _age;
};
// 这里需要指定PrintPersonInfo是属于Person这个类域
void Person::PrintPersonInfo()
{
    cout << _name << " "<< _gender << " " << _age << endl;
}

3.4 类的实例化 

用类类型创建对象的过程,称为类的实例化

  • 类是对对象进行描述的,是一个模型一样的东西,限定了类有哪些成员,定义出一个类,并没有分配实际的内存空间来存储它;比如:入学时填写的学生信息表,表格就可以看成是一个类,来描述具体学生信息
  • 类就像谜语一样,对谜底来进行描述,谜底就是谜语的一个实例
  • 一个类可以实例化出多个对象,实例化出的对象 占用实际的物理空间,存储类成员变量
int main()
{
    Person._age = 100;   // 编译失败:error C2059: 语法错误:“.”
    return 0;
}

Person类是没有空间的,只有Person类实例化出的对象才有具体的年龄 

  • 类实例化出对象就像现实中使用建筑设计图建造出房子,类就像是设计图,只设计出需要什么东西,但是并没有实体的建筑存在,同样类也只是一个设计,实例化出的对象才能实际存储数据,占用物理空间

 

4.类对象模型 

4.1 如何计算类对象的大小

class A
{
public:
    void PrintA()
    {
        cout<<_a<<endl;
    }
private:
    char _a;
};

问题:类中既可以有成员变量,又可以有成员函数,那么一个类的对象中包含了什么?如何计算一个类的大小?

4.2 类对象的存储方式猜测

  • 对象中包含类的各个成员

缺陷:每个对象中成员变量是不同的,但是调用同一份函数,如果按照此种方式存储,当一个类创建多个对象时,每个对象中都会保存一份代码,相同代码保存多次,浪费空间。那么如何解决呢?

  • 代码只保存一份,在对象中保存存放代码的地址

  •  只保存成员变量,成员函数存放在公共的代码段

问题:对于上述三种存储方式,那计算机到底是按照那种方式来存储的?

 类中既有成员变量,又有成员函数
class A1 {
public:
    void f1(){}
private:
    int _a;
};
 类中仅有成员函数
class A2 {
public:
   void f2() {}
};
 类中什么都没有---空类
class A3
{};

结论:一个类的大小,实际就是该类中“成员变量”之和,当然要注意内存对齐

注意空类的大小,空类比较特殊,编译器给了空类一个字节来唯一标识这个类的对象

4.3 结构体内存对齐规则

  • 第一个成员在与结构体偏移量为0的地址处
    其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处
  • 注意:对齐数 = 编译器默认的一个对齐数 与 该成员大小的较小值
    VS中默认的对齐数为8
  • 结构体总大小为:最大对齐数(所有变量类型最大者与默认对齐参数取最小)的整数倍
  • 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍

具体的内存对齐说明在《C语言专栏-结构体-结构体内存对齐》:

Day_16 结构体-CSDN博客

C语言--结构体内存对齐规则_结构体对齐原则-CSDN博客

5.this指针 

5.1 this指针的引出

我们先来定义一个日期类 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, d2;
	d1.Init(2022, 1, 11);
	d2.Init(2022, 1, 12);
	d1.Print();
	d2.Print();
	return 0;
}

对于上述类,有这样的一个问题:

Date类中有 Init 与 Print 两个成员函数,函数体中没有关于不同对象的区分,那当d1调用 Init 函数时,该函数是如何知道应该设置d1对象,而不是设置d2对象呢?

C++中通过引入this指针解决该问题,即:C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有“成员变量”的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成

5.2 this指针的特性

  1. this指针的类型:类类型* const,即成员函数中,不能给this指针赋值
  2. 只能在“成员函数”的内部使用
  3. this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针
  4. this指针是“成员函数”第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递

面试题: 

  1. this指针存在哪里?
  2. this指针可以为空吗?

C++中this指针存储的位置 && this是否可以是nullptr_this指针存放在哪里-CSDN博客

6.构造函数和析构函数

6.1 类的6个默认成员函数

如果一个类中什么成员都没有,简称为空类。

空类中真的什么都没有吗?并不是,任何类在什么都不写时,编译器会自动生成以下6个默认成员函数

默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数。

class Date {};

6.2 构造函数

6.2.1 概念

对于以下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;
	d1.Init(2022, 7, 5);
	d1.Print();
	Date d2;
	d2.Init(2022, 7, 6);
	d2.Print();
	return 0;
}

对于Date类,可以通过 Init 公有方法给对象设置日期,但如果每次创建对象时都调用该方法设置信息,未免有点麻烦,那能否在对象创建时,就将信息设置进去呢?

构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成员都有 一个合适的初始值,并且在对象整个生命周期内只调用一次

6.2.2 特性

构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是初始化对象

其特征如下:

  1. 函数名与类名相同。
  2. 无返回值。
  3. 对象实例化时编译器自动调用对应的构造函数。
  4. 构造函数可以重载
    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函数,该函数无参,返回一个日期类型的对象
    	// warning C4930: “Date d3(void)”: 未调用原型函数(是否是有意用变量定义的?)
    	Date d3();
    }
  5. 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成
    class Date
    {
    public:
    	/*
    	// 如果用户显式定义了构造函数,编译器将不再生成
    	Date(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类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数
    	// 将Date类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再生成
    	// 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
    	Date d1;
    	return 0;
    }
  6. 关于编译器生成的默认成员函数,很多童鞋会有疑惑:不实现构造函数的情况下,编译器会生成默认的构造函数。但是看起来默认构造函数又没什么用?d对象调用了编译器生成的默认构造函数,但是d对象_year/_month/_day,依旧是随机值。也就说在这里编译器生成的默认构造函数并没有什么用??
    解答:C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的数据类型,如:int/char...,自定义类型就是我们使用class/struct/union等自己定义的类型,看看下面的程序,就会发现编译器生成默认的构造函数会对自定类型成员_t调用的它的默认成员函数
     

    class Time
    {
    public:
    	Time()
    	{
    		cout << "Time()" << endl;
    		_hour = 0;
    		_minute = 0;
    		_second = 0;
    	}
    private:
    	int _hour;
    	int _minute;
    	int _second;
    };
    class Date
    {
    private:
    	// 基本类型(内置类型)
    	int _year;
    	int _month;
    	int _day;
    	// 自定义类型
    	Time _t;
    };
    int main()
    {
    	Date d;
    	return 0;
    }

    注意:C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在类中声明时可以给默认值
     

    class Time
    {
    public:
    	Time()
    	{
    		cout << "Time()" << endl;
    		_hour = 0;
    		_minute = 0;
    		_second = 0;
    	}
    private:
    	int _hour;
    	int _minute;
    	int _second;
    };
    class Date
    {
    private:
    	// 基本类型(内置类型)
    	int _year = 1970;
    	int _month = 1;
    	int _day = 1;
    	// 自定义类型
    	Time _t;
    };
    int main()
    {
    	Date d;
    	return 0;
    }
  7. 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数

    class Date
    {
    public:
    	Date()
    	{
    		_year = 1900;
    		_month = 1;
    		_day = 1;
    	}
    	Date(int year = 1900, int month = 1, int day = 1)
    	{
    		_year = year;
    		_month = month;
    		_day = day;
    	}
    private:
    	int _year;
    	int _month;
    	int _day;
    };
    // 以下测试函数能通过编译吗?
    void Test()
    {
    	Date d1;
    }

 

6.3 析构函数  

6.3.1 概念

通过前面构造函数的学习,我们知道一个对象是怎么来的,那一个对象又是怎么没呢的?
析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作

6.3.2 特性

析构函数是特殊的成员函数,其特征如下:

  1. 析构函数名是在类名前加上字符 ~。
  2. 无参数无返回值类型。
  3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载
  4. 对象生命周期结束时,C++编译系统系统自动调用析构函数
    typedef int DataType;
    class Stack
    {
    public:
    	Stack(size_t capacity = 3)
    	{
    		_array = (DataType*)malloc(sizeof(DataType) * capacity);
    		if (NULL == _array)
    		{
    			perror("malloc申请空间失败!!!");
    			return;
    		}
    		_capacity = capacity;
    		_size = 0;
    	}
    	void Push(DataType data)
    	{
    		// CheckCapacity();
    		_array[_size] = data;
    		_size++;
    	}
    	// 其他方法...
    	~Stack()
    	{
    		if (_array)
    		{
    			free(_array);
    			_array = NULL;
    			_capacity = 0;
    			_size = 0;
    		}
    	}
    private:
    	DataType* _array;
    	int _capacity;
    	int _size;
    };
    void TestStack()
    {
    	Stack s;
    	s.Push(1);
    	s.Push(2);
    }
  5. 关于编译器自动生成的析构函数,是否会完成一些事情呢?下面的程序我们会看到,编译器生成的默认析构函数,对自定类型成员调用它的析构函数
     

    class Time
    {
    public:
    	~Time()
    	{
    		cout << "~Time()" << endl;
    	}
    private:
    	int _hour;
    	int _minute;
    	int _second;
    };
    class Date
    {
    private:
    	// 基本类型(内置类型)
    	int _year = 1970;
    	int _month = 1;
    	int _day = 1;
    	// 自定义类型
    	Time _t;
    };
    int main()
    {
    	Date d;
    	return 0;
    }

    // 程序运行结束后输出:~Time()

    // 在main方法中根本没有直接创建Time类的对象,为什么最后会调用Time类的析构函数?

    // 因为:main方法中创建了Date对象d,而d中包含4个成员变量,其中_year, _month,_day三个是内置类型成员,销毁时不需要资源清理,最后系统直接将其内存回收即可;而_t是Time类对象,所以在d销毁时,要将其内部包含的Time类的_t对象销毁,所以要调用Time类的析构函数。但是:
     

    main函数中不能直接调用Time类的析构函数,实际要释放的是Date类对象,所以编译器会调用Date类的析构函数,而Date没有显式提供,则编译器会给Date类生成一个默认的析构函数,目的是在其内部调用Time类的析构函数,即当Date对象销毁时,要保证其内部每个自定义对象都可以正确销毁

    // main函数中并没有直接调用Time类析构函数,而是显式调用编译器为Date类生成的默认析构函数
     

    // 注意:创建哪个类的对象则调用该类的析构函数,销毁那个类的对象则调用该类的析构函数

  6. 如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,比如Date类;有资源申请时,一定要写,否则会造成资源泄漏,比如Stack类

7.拷贝构造函数 

7.1 概念

在现实生活中,可能存在一个与你一样的自己,我们称其为双胞胎

那在创建对象时,可否创建一个与已存在对象一某一样的新对象呢?

拷贝构造函数只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用

7.2 特征

拷贝构造函数也是特殊的成员函数,其特征如下:

  1. 拷贝构造函数是构造函数的一个重载形式
  2. 拷贝构造函数的参数只有一个必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用
    class Date
    {
    public:
    	Date(int year = 1900, int month = 1, int day = 1)
    	{
    		_year = year;
    		_month = month;
    		_day = day;
    	}
    	// Date(const Date& d)   // 正确写法
    	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. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝

    class Time
    {
    public:
    	Time()
    	{
    		_hour = 1;
    		_minute = 1;
    		_second = 1;
    	}
    	Time(const Time& t)
    	{
    		_hour = t._hour;
    		_minute = t._minute;
    		_second = t._second;
    		cout << "Time::Time(const Time&)" << endl;
    	}
    private:
    	int _hour;
    	int _minute;
    	int _second;
    };
    class Date
    {
    private:
    	// 基本类型(内置类型)
    	int _year = 1970;
    	int _month = 1;
    	int _day = 1;
    	// 自定义类型
    	Time _t;
    };
    int main()
    {
    	Date d1;
    
    	// 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
    	// 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数
    	Date d2(d1);
    	return 0;
    }

    注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定

    义类型是调用其拷贝构造函数完成拷贝的

  4. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?

    当然像日期类这样的类是没必要的。那么下面的类呢?验证一下试试?

    // 这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
    typedef int DataType;
    class Stack
    {
    public:
    	Stack(size_t capacity = 10)
    	{
    		_array = (DataType*)malloc(capacity * sizeof(DataType));
    		if (nullptr == _array)
    		{
    			perror("malloc申请空间失败");
    			return;
    		}
    		_size = 0;
    		_capacity = capacity;
    	}
    	void Push(const DataType& data)
    	{
    		// CheckCapacity();
    		_array[_size] = data;
    		_size++;
    	}
    	~Stack()
    	{
    		if (_array)
    		{
    			free(_array);
    			_array = nullptr;
    			_capacity = 0;
    			_size = 0;
    		}
    	}
    private:
    	DataType* _array;
    	size_t _size;
    	size_t _capacity;
    };
    int main()
    {
    	Stack s1;
    	s1.Push(1);
    	s1.Push(2);
    	s1.Push(3);
    	s1.Push(4);
    	Stack s2(s1);
    	return 0;
    }
    ​​

    注意:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请

    时,则拷贝构造函数是一定要写的,否则就是浅拷贝

  • 拷贝构造函数典型调用场景:

        使用已存在对象创建新对象

        函数参数类型为类类型对象

        函数返回值类型为类类型对象

     
    class Date
    {
    public:
    	Date(int year, int minute, int day)
    	{
    		cout << "Date(int,int,int):" << this << endl;
    	}
    	Date(const Date& d)
    	{
    		cout << "Date(const Date& d):" << this << endl;
    	}
    	~Date()
    	{
    		cout << "~Date():" << this << endl;
    	}
    private:
    	int _year;
    	int _month;
    	int _day;
    };
    Date Test(Date d)
    {
    	Date temp(d);
    	return temp;
    }
    int main()
    {
    	Date d1(2022, 1, 13);
    	Test(d1);
    	return 0;
    }

    ​​

    为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用

8.友元

友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多用

友元分为:友元函数友元类

8.1 友元函数

问题:现在尝试去重载operator<<,然后发现没办法将operator<<重载成成员函数。因为cout的输出流对象和隐含的this指针在抢占第一个参数的位置。this指针默认是第一个参数也就是左操作数了,但是实际使用中cout需要是第一个形参对象,才能正常使用。所以要将operator<<重载成全局函数。但又会导致类外没办法访问成员,此时就需要友元来解决。operator>>同理。

class Date
{
public:
	Date(int year, int month, int day)
		: _year(year)
		, _month(month)
		, _day(day)
	{}
	// d1 << cout; -> d1.operator<<(&d1, cout); 不符合常规调用
	// 因为成员函数第一个参数一定是隐藏的this,所以d1必须放在<<的左侧
	ostream& operator<<(ostream& _cout)
	{
		_cout << _year << "-" << _month << "-" << _day << endl;
		return _cout;
	}
private:
	int _year;
	int _month;
	int _day;
};

友元函数可以直接访问类的私有成员,它是定义在类外部普通函数,不属于任何类,但需要在类的内部声明,声明时需要加friend关键字

class Date
{
	friend ostream& operator<<(ostream& _cout, const Date& d);
	friend istream& operator>>(istream& _cin, Date& d);
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}
private:
	int _year;
	int _month;
	int _day;
};
ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << "-" << d._month << "-" << d._day;
	return _cout;
}
istream& operator>>(istream& _cin, Date& d)
{
	_cin >> d._year;
	_cin >> d._month;
	_cin >> d._day;
	return _cin;
}
int main()
{
	Date d;
	cin >> d;
	cout << d << endl;
	return 0;
}

说明:

  • 友元函数可访问类的私有和保护成员,但不是类的成员函数
  • 友元函数不能用const修饰
  • 友元函数可以在类定义的任何地方声明,不受类访问限定符限制
  • 一个函数可以是多个类的友元函数
  • 友元函数的调用与普通函数的调用原理相同

8.2 友元类

友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。

  • 友元关系是单向的,不具有交换性
    比如上述Time类和Date类,在Time类中声明Date类为其友元类,那么可以在Date类中直接访问Time类的私有成员变量,但想在Time类中访问Date类中私有的成员变量则不行
  • 友元关系不能传递
    如果C是B的友元, B是A的友元,则不能说明C时A的友元
  • 友元关系不能继承
class Time
{
	friend class Date;
    // 声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成员变量
public:
	Time(int hour = 0, int minute = 0, int second = 0)
		: _hour(hour)
		, _minute(minute)
		, _second(second)
	{}

private:
	int _hour;
	int _minute;
	int _second;
};
class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
		: _year(year)
		, _month(month)
		, _day(day)
	{}

	void SetTimeOfDate(int hour, int minute, int second)
	{
		// 直接访问时间类私有的成员变量
		_t._hour = hour;
		_t._minute = minute;
		_t._second = second;
	}

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

9.内部类和匿名对象 

9.1 内部类

1.概念

概念:如果一个类定义在另一个类的内部,这个内部类就叫做内部类。内部类是一个独立的类,它不属于外部类,更不能通过外部类的对象去访问内部类的成员。外部类对内部类没有任何优越的访问权限

注意:内部类就是外部类的友元类,参见友元类的定义,内部类可以通过外部类的对象参数来访问外部类中的所有成员。但是外部类不是内部类的友元

2.特性

特性:

  1. 内部类可以定义在外部类的public、protected、private都是可以的
  2. 注意内部类可以直接访问外部类中的static成员,不需要外部类的对象/类名
  3. sizeof(外部类)=外部类,和内部类没有任何关系
class A
{
private:
    static int k;
    int h;
public:
    class B // B天生就是A的友元
    {
    public:
        void foo(const A& a)
        {
            cout << k << endl;//OK
            cout << a.h << endl;//OK
        }
    };
};
int A::k = 1;
int main()
{
    A::B b;
    b.foo(A());
    
    return 0;
}

9.2 匿名对象 

class A
{
public:
    A(int a = 0)
    :_a(a)
    {
        cout << "A(int a)" << endl;
    }
    ~A()
    {
        cout << "~A()" << endl;
    }
private:
    int _a;
};
class Solution {
public:
    int Sum_Solution(int n) 
    {
        //...
        return n;
    }
};
int main()
{
    A aa1;
    // 不能这么定义对象,因为编译器无法识别下面是一个函数声明,还是对象定义
    //A aa1();
    // 但是我们可以这么定义匿名对象,匿名对象的特点不用取名字,
    // 但是他的生命周期只有这一行,我们可以看到下一行他就会自动调用析构函数
    A();
    A aa2(2);
    // 匿名对象在这样场景下就很好用
    Solution().Sum_Solution(10);
    return 0;
}

9.3 拷贝对象时的一些编译器优化 

在传参和传返回值的过程中,一般编译器会做一些优化,减少对象的拷贝,这个在一些场景下还是非常有用的

class A
{
public:
	A(int a = 0)
		:_a(a)
	{
		cout << "A(int a)" << endl;
	}
	A(const A& aa)
		:_a(aa._a)
	{
		cout << "A(const A& aa)" << endl;
	}A& operator=(const A& aa)
	{
		cout << "A& operator=(const A& aa)" << endl;
		if (this != &aa)
		{
			_a = aa._a;
		}
		return *this;
	}
	~A()
	{
		cout << "~A()" << endl;
	}
private:
	int _a;
};
void f1(A aa)
{}
A f2()
{
	A aa;
	return aa;
}
int main()
{
	// 传值传参
	A aa1;
	f1(aa1);
	cout << endl;
	// 传值返回
	f2();
	cout << endl;
	// 隐式类型,连续构造+拷贝构造->优化为直接构造
	f1(1);
	// 一个表达式中,连续构造+拷贝构造->优化为一个构造
	f1(A(2));
	cout << endl;
	// 一个表达式中,连续拷贝构造+拷贝构造->优化一个拷贝构造
	A aa2 = f2();
	cout << endl;
	// 一个表达式中,连续拷贝构造+赋值重载->无法优化
	aa1 = f2();
	cout << endl;
	return 0;
}

10.定位new表达式(placement-new) 

 定位new表达式是在已分配的原始内存空间中调用构造函数初始化一个对象

使用格式:

new (place_address) type  或者  new (place_address) type(initializer-list)

place_address必须是一个指针,initializer-list是类型的初始化列表

使用场景:

定位new表达式在实际中一般是配合内存池使用。因为内存池分配出的内存没有初始化,所以如果是自定义类型的对象,需要使用new的定义表达式进行显示调构造函数进行初始化

class A
{
public:
	A(int a = 0)
		: _a(a)
	{
		cout << "A():" << this << endl;
	}
	~A()
	{
		cout << "~A():" << this << endl;
	}
private:
	int _a;
};// 定位new/replacement new
int main()
{
	// p1现在指向的只不过是与A对象相同大小的一段空间,还不能算是一个对象,因为构造函数没有执行
	A* p1 = (A*)malloc(sizeof(A));
	new(p1)A; // 注意:如果A类的构造函数有参数时,此处需要传参
	p1->~A();
	free(p1);
	A* p2 = (A*)operator new(sizeof(A));
	new(p2)A(10);
	p2->~A();
	operator delete(p2);
	return 0;
}

11.日期类的实现-Class Date 

 代码实现

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Date {
public:
	// 获取某年某月的天数
	int GetMonthDay(int year, int month)
	{
		static int monteDays[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			return 29;
		}
		return monteDays[month];
		/*if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
		{
			return 31;
		}
		else if (month == 2)
		{
			if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
			{
				return 29;
			}
			else
			{
				return 28;
			}
		}
		else
		{
			return 30;
		}*/
	}
	// 全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	// 拷贝构造函数
    // d2(d1)
	Date(const Date& d)
	{
		this->_year = d._year;
		this->_month = d._month;
		this->_day = d._day;
	}
	// 赋值运算符重载
	//d2 = d3 -> d2.operator=(&d2, d3)
	Date& operator=(const Date& d)
	{
		if (this != &d)
		{
			this->_year = d._year;
			this->_month = d._month;
			this->_day = d._day;
		}
		return *this;
	}
	// 析构函数
	~Date()
	{
		;
	}
	// 日期+=天数
	Date& operator+=(int day)
	{
		_day += day;
		while (_day > GetMonthDay(_year, _month))
		{
			_day -= GetMonthDay(_year, _month);
			++_month;
			if (_month == 13)
			{
				++_year;
				_month = 1;
			}
		}
		return *this;
	}
	// 日期+天数
	Date operator+(int day)
	{
		/*Date tmp(*this);
		tmp._day += day;
		while (tmp._day > GetMonthDay(tmp._year, tmp._month))
		{
			tmp._day -= GetMonthDay(tmp._year, tmp._month);
			++tmp._month;
			if (tmp._month == 13)
			{
				++tmp._year;
				tmp._month = 1;
			}
		}
		return tmp;*/
		Date tmp(*this);
		tmp += day;
		return tmp;
	}
	// 日期-=天数
	Date& operator-=(int day)
	{
		_day -= day;
		while (_day <= 0)
		{
			--_month;
			if (_month == 0)
			{
				--_year;
				_month = 12;
			}
			_day += GetMonthDay(_year, _month);
		}
		return *this;
	}
	// 日期-天数
	Date operator-(int day)
	{
		//Date tmp = *this;
		Date tmp(*this);
		tmp -= day;
		return tmp;
	}

	// 前置++
	Date& operator++()
	{
		*this += 1;
		return *this;
	}
	// 后置++
	Date operator++(int)
	{
		Date tmp = *this;
		*this += 1;
		return tmp;
	}
	// 后置--
	Date operator--(int)
	{
		Date tmp = *this;
		*this -= 1;
		return tmp;
	}
	// 前置--
	Date& operator--()
	{
		*this -= 1;
		return *this;
	}
	// >运算符重载
	bool operator>(const Date& d)
	{
		if (this->_year > d._year)
		{
			return true;
		}
		else if (this->_year == d._year)
		{
			if (this->_month > d._month)
			{
				return true;
			}
			else if (this->_month == d._month)
			{
				if (this->_day > d._day)
				{
					return true;
				}
			}
		}
		return false;
	}
	// ==运算符重载
	bool operator==(const Date& d)
	{
		return _year==d._year
			&& _month==d._month
			&& _day==d._day;
	}
	// >=运算符重载
	bool operator >= (const Date& d)
	{
		return (*this > d)||(*this==d);
		/*if (this->_year > d._year)
		{
			return true;
		}
		else if (this->_year == d._year)
		{
			if (this->_month > d._month)
			{
				return true;
			}
			else if (this->_month == d._month)
			{
				if (this->_day >= d._day)
				{
					return true;
				}
			}
		}
		return false;*/
	}
	// <运算符重载
	bool operator < (const Date& d)
	{
		return !(*this >= d);
		/*if (this->_year < d._year)
		{
			return true;
		}
		else if (this->_year == d._year)
		{
			if (this->_month < d._month)
			{
				return true;
			}
			else if (this->_month == d._month)
			{
				if (this->_day < d._day)
				{
					return true;
				}
			}
		}
		return false;*/
	}
	// <=运算符重载
	bool operator <= (const Date& d)
	{
		return !(*this > d);
		/*if (this->_year < d._year)
		{
			return true;
		}
		else if (this->_year == d._year)
		{
			if (this->_month < d._month)
			{
				return true;
			}
			else if (this->_month == d._month)
			{
				if (this->_day <= d._day)
				{
					return true;
				}
			}
		}
		return false;*/
	}
	// !=运算符重载
	bool operator != (const Date& d)
	{
		return !(*this == d);
		/*if (this->_year == d._year)
		{
			if (this->_month == d._month)
			{
				if (this->_day == d._day)
				{
					return true;
				}
			}
		}*/
		return false;
	}
	// 日期-日期 返回天数
	int operator-(const Date& d)
	{
		int flag = 1;
		Date max = *this;
		Date min = d;
		if (*this < d)
		{
			int flag = -1;
			max = d;
			min = *this;
		}
		int n = 0;
		while (min != max)
		{
			++min;
			++n;
		}
		return n * flag;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1;//1900/1/1
	Date d2(d1);
	Date d3(2024,1,28);//2024/1/28
	d2.operator=(d3);//d2=d3
	Date d4(2000,1,1);
	Date d5(2000,1,1);

	cout << d1.operator<(d3) << endl;
	cout << d3.operator<(d1) << endl;
	
	cout << d2.operator==(d3) << endl;
	cout << d1.operator==(d3) << endl;

	cout << d1.operator>(d2) << endl;
	cout << d2.operator>(d1) << endl;

	cout << d1.GetMonthDay(2000, 1) << endl;

	cout << d4.operator>=(d5) << endl;
	cout << d4.operator>(d5) << endl;
	cout << d4.operator<=(d5) << endl;
	cout << d4.operator<(d5) << endl;
	cout << d4.operator!=(d5) << endl;
	cout << d4.operator!=(d3) << endl;

	Date d6(2020, 1, 1);
	d6.operator+=(20);
	Date d7 = d6.operator+(30);
	Date d8(2024, 1, 30);
	d8.operator-=(30);
	Date d9 = d8.operator-(30);

	Date d10(2000, 1, 30);
	//Date D1 = d10.operator++(0);//d10++
	//Date D2 = d10.operator--(0);//d10--;
	//Date D3 = d10.operator++();//++d10;
	//Date D4 = d10.operator--();//--d10;
	d10++;
	d10--;
	++d10;
	--d10;

	Date d11(2024, 1, 30);
	Date d12(2024, 8, 1);
	cout << d12 - d11 << endl;
	cout << d11 - d12 << endl;
	return 0;
}

测试截图 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐