• 【C++】类和对象(中)


    一、类的6个默认成员函数

    如果一个类中什么成员都没有,简称为空类。但是空类中并不是真的什么都没有,任何类在什么都不写的时候,编译器会自动生成以下 6 个默认成员函数。
    默认成员函数用户没有显式实现,编译器会生成的成员函数称为默认成员函数。
    1. class Date{
    2. // 空类
    3. };

    二、构造函数

    1、概念

    1. class Date
    2. {
    3. public:
    4. void Init(int year, int month, int day)
    5. {
    6. _year = year;
    7. _month = month;
    8. _day = day;
    9. }
    10. void Print()
    11. {
    12. cout << _year << "-" << _month << "-" << _day << endl;
    13. }
    14. private:
    15. int _year;
    16. int _month;
    17. int _day;
    18. };
    19. int main()
    20. {
    21. Date d1;
    22. d1.Init(2023, 1, 26);
    23. d1.Print();
    24. Date d2;
    25. d2.Init(2023, 8, 9);
    26. d2.Print();
    27. return 0;
    28. }
    对于 Date 类,可以通过 Init 公有方法给对象设置日期,但如果每次创建对象时都调用该方法设置信息,未免有点麻烦,或者有时候忘记初始化,那能否在对象创建时,就将信息设置进去呢?
    构造函数是一个特殊的成员函数 名字与类名相同 ,创建类类型对象时由编译器自动调用,以保证每个数据成员都有 一个合适的初始值,并且在对象整个生命周期内 只调用一次

    2、特性

    构造函数是特殊的成员函数,不能以普通函数的定义和调用规则去理解,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象,而是 初始化对象

    特征:

    1. 函数名类名相同
    2. 无返回值不用写 void
    3. 对象实例化时编译器自动调用对应的构造函数。
    4. 构造函数可以重载
    1. class Date
    2. {
    3. public:
    4. // 1、无参构造函数
    5.    Date()
    6.    {
    7. _year = 1;
    8. _month = 1;
    9.        _day = 1;
    10. }
    11. // 写法相同
    12. /*Date(int year = 1, int month = 1, int day = 1)
    13.    {
    14. _year = year;
    15. _month = month;
    16.        _day = day;
    17.    }*/
    18.  
    19.    // 2、带参构造函数
    20.    Date(int year, int month, int day)
    21.    {
    22. _year = year;
    23. _month = month;
    24.        _day = day;
    25.    }
    26. private:
    27. int _year;
    28.    int _month;
    29.    int _day;
    30. };
    31.  
    32. void TestDate()
    33. {
    34. Date d1; // 调用无参构造函数
    35.    Date d2(2023, 9, 12); // 调用带参的构造函数
    36.  
    37.    Date d3(); // 声明了d3函数,该函数无参,返回一个日期类型的对象
    38. // warning C4930: “Date d3(void)”: 未调用原型函数(是否是有意用变量定义呢?)
    39. }

    注意:如果通过无参构造函数创建对象时对象后面不用跟括号,否则就成了函数声明。


    5、如果类中没有显式定义构造函数,则 C++ 编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。 

    1. class Date
    2. {
    3. public:
    4. /*
    5. // 如果用户显式定义了构造函数,编译器将不再生成
    6. Date(int year, int month, int day)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. */
    13. void Print()
    14. {
    15. cout << _year << "-" << _month << "-" << _day << endl;
    16. }
    17.  
    18. private:
    19. int _year;
    20. int _month;
    21. int _day;
    22. };
    23.  
    24. int main()
    25. Date d1;
    26. // 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
    27. return 0;
    28. }

    将 Date 类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数。

    将 Date 类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再生成。


    6、关于编译器生成的默认成员函数,在不实现构造函数的情况下,编译器会生成默认的构造函数。但是看起来默认构造函数又没什么用?d 对象调用了编译器生成的默认构造函数,但是 d 对象 _year / _month / _day,依旧是随机值。也就说在这里编译器生成的默认构造函数并没有什么用?

    C++ 把类型分成内置类型(基本类型)和自定义类型
    • 内置类型就是语言提供的数据类型,如:int / double / char / 指针等。
    • 自定义类型就是我们使用 class / struct / union 等自己定义的类型。

    从下面的代码中可以发现编译器生成默认的构造函数会对自定类型成员 _t 调用的它的默认成员函数。也就是说,默认生成的构造函数对内置类型成员不作处理,对自定义类型成员去调用它的默认构造函数这个设计是 C++ 早期设计的一个缺陷,本来应该内置类型也一并处理。

    1. 对于类中的内置类型成员 —> 不处理(为随机值,除非声明时给了缺省值 - C++11)
    2. 对于类中的自定义类型成员 —> 自动调用它的默认构造函数(不要参数就可以调用的,比如 无参构造函数 或 全缺省构造函数
    1. class Time
    2. {
    3. public:
    4. Time()
    5. {
    6. cout << "Time()" << endl;
    7. _hour = 0;
    8. _minute = 0;
    9. _second = 0;
    10. }
    11. private:
    12. int _hour;
    13. int _minute;
    14. int _second;
    15. };
    16. class Date
    17. {
    18. private:
    19. // 基本类型(内置类型)
    20. int _year;
    21. int _month;
    22. int _day;
    23. // 自定义类型
    24. Time _t;
    25. };
    26. int main()
    27. {
    28. Date d;
    29. return 0;
    30. }
    注意 :C++11 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在
    类中声明时可以给默认值,注意这里不是初始化,是声明,给缺省值。
    1. class Time
    2. {
    3. public:
    4. Time()
    5. {
    6. cout << "Time()" << endl;
    7. _hour = 0;
    8. _minute = 0;
    9. _second = 0;
    10. }
    11. private:
    12. int _hour;
    13. int _minute;
    14. int _second;
    15. };
    16. class Date
    17. {
    18. private:
    19. // 基本类型(内置类型)
    20. // 给缺省值
    21. int _year = 1; // 声明
    22. int _month = 1;
    23. int _day = 1;
    24. // 自定义类型
    25. Time _t;
    26. };
    27. int main()
    28. {
    29. Date d;
    30. return 0;
    31. }

    7、无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。

    注意 :默认构造函数:(不传参数就可以调用的)
    1. 无参构造函数。
    2. 全缺省构造函数。
    3. 没写,编译器默认生成的构造函数
    1. class Date
    2. {
    3. public:
    4. // 1、无参构造函数
    5. Date()
    6. {
    7. _year = 1;
    8. _month = 1;
    9. _day = 1;
    10. }
    11. // 2、带参构造函数
    12. Date(int year = 1, int month = 1, int day = 1)
    13. {
    14. _year = year;
    15. _month = month;
    16. _day = day;
    17. }
    18. private:
    19. int _year;
    20. int _month;
    21. int _day;
    22. };
    23. int main()
    24. {
    25. Date d1; // 无法通过编译 - 调用存在二义性
    26. return 0;
    27. }

    构造函数特点不用传参数就可以调用。

    1. 一般的类都不会让编译器默认生成构造函数,大部分都会自己去写。显示写一个全缺省,很好用。
    2. 特殊情况才会默认生成构造函数(例如 Myqueue 这样的类)。
    3. 每个类最好都要提供默认构造函数。

    三、析构函数

    1、概念

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

    构造函数是为了替代 Init,析构函数是为了替代 Destroy。 


    2、特性 

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

    1. 析构函数名是在类名前加上字符 ~
    2. 无参数无返回值类型
    3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意析构函数不能重载
    4. 对象生命周期结束时,C++ 编译系统系统自动调用析构函数。
    5. 后定义的先析构,跟数据结构中的栈性质相同。
    1. typedef int DataType;
    2. class Stack
    3. {
    4. public:
    5. Stack(size_t capacity = 4)
    6. {
    7. _array = (DataType*)malloc(sizeof(DataType) * capacity);
    8. if (NULL == _array)
    9. {
    10. perror("malloc申请空间失败!!!");
    11. return;
    12. }
    13. _capacity = capacity;
    14. _size = 0;
    15. }
    16. void Push(DataType data)
    17. {
    18. // CheckCapacity();
    19. _array[_size] = data;
    20. _size++;
    21. }
    22. // 其他方法...
    23. ~Stack()
    24. {
    25. if (_array)
    26. {
    27. free(_array);
    28. _array = NULL;
    29. _capacity = 0;
    30. _size = 0;
    31. }
    32. }
    33. private:
    34. DataType* _array;
    35. int _capacity;
    36. int _size;
    37. };
    38. void TestStack()
    39. {
    40. Stack s;
    41. s.Push(1);
    42. s.Push(2);
    43. }

    6、关于编译器自动生成的析构函数,从下面的程序可以看到,编译器生成的默认析构函数,对自定义类型成员调用它的析构函数。

    1. 对于类中的内置类型成员 —> 不处理。

    2. 对于类中的自定义类型成员 —> 调用它的析构函数完成清理工作。

    1. class Time
    2. {
    3. public:
    4. ~Time()
    5. {
    6. cout << "~Time()" << endl;
    7. }
    8. private:
    9. int _hour;
    10. int _minute;
    11. int _second;
    12. };
    13. class Date
    14. {
    15. private:
    16. // 基本类型(内置类型)
    17. int _year = 1970;
    18. int _month = 1;
    19. int _day = 1;
    20. // 自定义类型
    21. Time _t;
    22. };
    23. int main()
    24. {
    25. Date d;
    26. return 0;
    27. }
    28. // 程序运行结束后输出:~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 类生成的默认析构函数。


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


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

    默认生成析构函数的特点(跟构造函数类似):

    1. 一些内置类型的类不作处理。比如 Date这样的类,没有资源需要清理;比如 MyQueue 也可以不写,默认生成的就可以。
    2. 自定义类型成员回去调用它的析构函数,比如:Stack、Queue...

    四、拷贝构造函数

    1、概念

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

    2、特征

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

    1. 拷贝构造函数构造函数的一个重载形式
    2. 拷贝构造函数的参数只有一个必须是类类型对象的引用,使用传值方式编译器会直接报错,因为会引发无穷递归调用。
    1. class Date
    2. {
    3. public:
    4. Date(int year = 1, int month = 1, int day = 1)
    5. {
    6. _year = year;
    7. _month = month;
    8. _day = day;
    9. }
    10. Date(const Date& d) // 正确写法
    11.    //Date(const Date d)   // 错误写法:编译报错,会引发无穷递归
    12. {
    13. _year = d._year;
    14. _month = d._month;
    15. _day = d._day;
    16. }
    17. private:
    18. int _year;
    19. int _month;
    20. int _day;
    21. };
    22. int main()
    23. {
    24. Date d1;
    25. Date d2(d1);
    26. return 0;
    27. }

    使用引用作为拷贝构造函数的参数可以有效避免无穷递归调用的问题。因为引用在初始化时不会调用拷贝构造函数,而是直接将引用绑定到已经存在的对象上。

    tips:建议拷贝构造函数的参数类型前加上 const,防止其值误被修改。


    3、若未显示定义,编译器会生成默认的拷贝构造函数。默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝。

    浅拷贝:

    1. 一个对象修改会影响另一个对象。
    2. 会析构两次,程序崩溃。

    解决方法:自己实现深拷贝。 

    如果没有显式定义,编译器自动生成的拷贝构造函数,它会做哪些事情呢?

    1. 对于类中的内置类型成员 —> 值拷贝
    2. 对于类中的自定义类型成员 —> 自动调用它的拷贝构造函数来完成拷贝初始化。
    1. class Time
    2. {
    3. public:
    4. Time()
    5. {
    6. _hour = 1;
    7. _minute = 1;
    8. _second = 1
    9. }
    10. Time(const Time& t)
    11. {
    12. _hour = t._hour;
    13. _minute = t._minute;
    14. _second = t._second;
    15. cout << "Time::Time(const Time&)" << endl;
    16. }
    17. private:
    18. int _hour;
    19. int _minute;
    20. int _second;
    21. };
    22. class Date
    23. {
    24. private:
    25. // 基本类型(内置类型)
    26. int _year = 1;
    27. int _month = 1;
    28. int _day = 1;
    29. // 自定义类型
    30. Time _t;
    31. };
    32. int main()
    33. {
    34. Date d1;
    35. Date d2(d1);
    36. return 0;
    37. }

    用已经存在的 d1 拷贝构造 d2,此处会调用 Date 类的拷贝构造函数。但 Date 类并没有显式定义拷贝构造函数,则编译器会给 Date 类生成一个默认的拷贝构造函数。

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

    4、编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?当然像日期类这样的类是没必要的。那么下面的类呢?

    像日期类这样的类是没必要的。但有些需要深拷贝的类,其内部往往是很复杂的,是需要用户显式定义拷贝构造函数来完成深拷贝的。

    1. // 下面这个程序会崩溃掉,因为这里就需要深拷贝去解决。
    2. typedef int DataType;
    3. class Stack
    4. {
    5. public:
    6. Stack(size_t capacity = 10)
    7. {
    8. _array = (DataType*)malloc(capacity * sizeof(DataType));
    9. if (nullptr == _array)
    10. {
    11. perror("malloc申请空间失败");
    12. return;
    13. }
    14. size = 0;
    15. _capacity = capacity;
    16. }
    17. void Push(const DataType& data)
    18. {
    19. // CheckCapacity();
    20. _array[_size] = data;
    21. _size++;
    22. }
    23. ~Stack()
    24. {
    25. if (_array)
    26. {
    27. free(_array);
    28. _array = nullptr;
    29. _capacity = 0;
    30. _size = 0;
    31. }
    32. }
    33. private:
    34. DataType *_array;
    35. size_t _size;
    36. size_t _capacity;
    37. };
    38. int main()
    39. {
    40. Stack s1;
    41. s1.Push(1);
    42. s1.Push(2);
    43. s1.Push(3);
    44. s1.Push(4);
    45. Stack s2(s1); // 会造成指向的同一块区域的内容被两次释放
    46. return 0;
    47. }
    注意 :类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请 时,则拷贝构造函数是一定要写的,否则就是浅拷贝。

    如图:指向了同一块空间。

    image-20220417221717913

    那么会引发什么问题呢?会导致 _str 指向的空间被释放两次,引发程序崩溃

    image-20220417221809176


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

    1. 使用已存在对象创建新对象。
    2. 函数参数类型为类类型对象。
    3. 函数返回值类型为类类型对象。
    1. class Date
    2. {
    3. public:
    4. Date(int year, int minute, int day)
    5. {
    6. cout << "Date(int, int, int):" << this << endl;
    7. }
    8. Date(const Date& d)
    9. {
    10. cout << "Date(const Date& d):" << this << endl;
    11. }
    12. ~Date()
    13. {
    14. cout << "~Date():" << this << endl;
    15. }
    16. private:
    17. int _year;
    18. int _month;
    19. int _day;
    20. };
    21. Date Test(Date d)
    22. {
    23. Date temp(d);
    24. return temp;
    25. }
    26. int main()
    27. {
    28. Date d1(2023 ,9, 13);
    29. Test(d1);
    30. return 0;
    31. }

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

    一些类需要显示写拷贝和赋值,比如:Stack、Queue...

    一些类不需要显示写拷贝和赋值。比如 Date 这样的类,默认生成就会完成值拷贝 / 浅拷贝,比如 MyQueue 这样的类,默认生成就会调用它的自定义类型成员 Stack 的拷贝和赋值。


    五、赋值运算符重载

    1、运算符重载

    C++ 为了增强代码的可读性引入了 运算符重载 运算符重载是具有特殊函数名的函数,也具有其返回值类型函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
    1. 函数名字:关键字 operator 后面接需要重载的运算符符号
    2. 函数原型:返回值类型 operator 操作符(参数列表)

    内置类型可以直接使用运算符运算,编译器知道要如何运算。

    自定义类型无法直接使用运算符,编译器不知道要如何运算。

      注意
    • 不能通过连接其他符号来创建新的操作符:比如 operator@。
    • 重载操作符必须有一个类类型参数。
    • 用于内置类型的运算符,其含义不能改变,例如:内置的整型 +,不能改变其含义。
    • 作为类成员函数重载时,其形参看起来比操作数数目少 1,因为成员函数的第一个参数为隐藏的 this
    • .*   ::   sizeof   ?:   .  注意以上 5 个运算符不能重载 
    1. // 全局的operator==
    2. class Date
    3. {
    4. public:
    5. Date(int year = 1, int month = 1, int day = 1)
    6.   {
    7. _year = year;
    8.        _month = month;
    9.        _day = day;
    10.   }
    11. //private:
    12. int _year;
    13. int _month;
    14. int _day;
    15. };
    16. // 这里会发现运算符重载成全局的就需要成员变量是公有的,那么要如何保证封装性呢?
    17. // 这里其实可以用友元解决,或者干脆重载成成员函数。
    18. bool operator==(const Date& d1, const Date& d2)
    19. {
    20.    return d1._year == d2._year && d1._month == d2._month && d1._day == d2._day;
    21. }
    22. void Test ()
    23. {
    24.    Date d1(2023, 9, 13);
    25.    Date d2(2023, 9, 14);
    26.    cout << (d1 == d2) << endl;
    27. }

    运算符重载,一般有两种方式

    • 重载成类的成员函数(形参数目看起来比该运算符需要的参数少一个,因为成员函数有隐含的 this 指针,且函数的第一个形参就是 this 指针)。
    • 重载成类的友元函数(必须有一个参数要是类的对象)(一般不这样做,而是重载成成员函数)。

    下面这种写法更好: 

    1. class Date
    2. {
    3. public:
    4. Date(int year = 1, int month = 1, int day = 1)
    5. {
    6. _year = year;
    7.        _month = month;
    8.        _day = day;
    9.   }
    10.    
    11. // bool operator==(Date* this, const Date& d2)
    12.    bool operator==(const Date& d2) // 注意左操作数是隐藏的this,指向调用函数的对象
    13. {
    14.        return _year == d2._year && _month == d2._month && _day == d2._day;
    15. }
    16. private:
    17. int _year;
    18. int _month;
    19. int _day;
    20. };
    21. void Test ()
    22. {
    23.    Date d1(2023, 9, 13);
    24.    Date d2(2023, 9, 14);
    25.    cout << d1.operator==(d2) << endl; // d1.operator==(&d1, d2);
    26. }

    2、赋值运算符重载

    (1)赋值运算符重载格式
    • 参数类型const T&传递引用可以提高传参效率。
    • 返回值类型T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
    • 检测是否自己给自己赋值
    • 返回 *this :要复合连续赋值的含义。
    1. class Date
    2. {
    3. public :
    4. Date(int year = 1, int month = 1, int day = 1)
    5.   {
    6. _year = year;
    7.        _month = month;
    8.        _day = day;
    9.   }
    10. Date (const Date& d)
    11.   {
    12.        _year = d._year;
    13.        _month = d._month;
    14.        _day = d._day;
    15. return *this; // 支持连续赋值
    16.   }
    17. Date& operator=(const Date& d) // 传引用返回
    18. {
    19. if(this != &d) // 检测是否自己给自己赋值
    20.       {
    21.         _year = d._year;
    22.            _month = d._month;
    23.            _day = d._day;
    24.       }   
    25.        return *this;
    26. }
    27. private:
    28. int _year ;
    29. int _month ;
    30. int _day ;
    31. };
    32. void TestDate()
    33. {
    34. Date d1(2023, 9, 13);
    35. Date d2(d1);
    36. Date d3(2023, 11, 28);
    37. d2 = d1 = d3;
    38. }

    (2)赋值运算符只能重载成类的成员函数不能重载成全局函数
    1. class Date
    2. {
    3. public:
    4. Date(int year = 1900, int month = 1, int day = 1)
    5. {
    6. _year = year;
    7. _month = month;
    8. _day = day;
    9. }
    10. int _year;
    11. int _month;
    12. int _day;
    13. };
    14. // 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
    15. Date& operator=(Date& left, const Date& right)
    16. {
    17. if (&left != &right)
    18. {
    19. left._year = right._year;
    20. left._month = right._month;
    21. left._day = right._day;
    22. }
    23. return left;
    24. }

    编译失败:error C2801: “operator =”必须是非静态成员

    原因 :赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现
    一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值
    运算符重载只能是 类的成员函数

    (3)用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝
    注意 :内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。
    1. class Time
    2. {
    3. public:
    4. Time()
    5. {
    6. _hour = 1;
    7. _minute = 1;
    8. _second = 1;
    9. }
    10. Time& operator=(const Time& t)
    11. {
    12. if (this != &t)
    13. {
    14. _hour = t._hour;
    15. _minute = t._minute;
    16. _second = t._second;
    17. }
    18. return *this;
    19. }
    20. private:
    21. int _hour;
    22. int _minute;
    23. int _second;
    24. };
    25. class Date
    26. {
    27. private:
    28. // 基本类型(内置类型)
    29. int _year = 1;
    30. int _month = 1;
    31. int _day = 1;
    32. // 自定义类型
    33. Time _t;
    34. };
    35. int main()
    36. {
    37. Date d1;
    38. Date d2;
    39. d1 = d2;
    40. return 0;
    41. }

    既然编译器生成的默认赋值运算符重载函数已经可以完成字节序的值拷贝了,还需要自己实现吗?当然像日期类这样的类是没必要的。那么下面的类呢?

    像日期类这样的类是没必要的。但有些需要深拷贝的类,其内部往往是很复杂的,是需要用户显式定义赋值运算符重载函数来完成深拷贝的。

    1. // 下面这个程序会崩溃,这里需要用深拷贝去解决。
    2. typedef int DataType;
    3. class Stack
    4. {
    5. public:
    6. Stack(size_t capacity = 10)
    7. {
    8. _array = (DataType*)malloc(capacity * sizeof(DataType));
    9. if (nullptr == _array)
    10. {
    11. perror("malloc申请空间失败");
    12. return;
    13. }
    14. _size = 0;
    15. _capacity = capacity;
    16. }
    17. void Push(const DataType& data)
    18. {
    19. // CheckCapacity();
    20. _array[_size] = data;
    21. _size++;
    22. }
    23. ~Stack()
    24. {
    25. if (_array)
    26. {
    27. free(_array);
    28. _array = nullptr;
    29. _capacity = 0;
    30. _size = 0;
    31. }
    32. }
    33. private:
    34. DataType *_array;
    35. size_t _size;
    36. size_t _capacity;
    37. };
    38. int main()
    39. {
    40. Stack s1;
    41. s1.Push(1);
    42. s1.Push(2);
    43. s1.Push(3);
    44. s1.Push(4);
    45. Stack s2;
    46. s2 = s1;
    47. return 0;
    48. }

    注意:如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现。


    3、前置++和后置++重载

    1. class Date
    2. {
    3. public:
    4. Date(int year = 1, int month = 1, int day = 1)
    5. {
    6. _year = year;
    7. _month = month;
    8. _day = day;
    9. }
    10. Date& operator++() // 前置++:返回+1之后的结果。
    11. {
    12. _day += 1;
    13. return *this; // this 指向的对象函数结束后不会销毁,故以引用的方式返回提高效率。
    14. }
    15. Date operator++(int) // 后置++是先使用后+1,因此需要返回+1之前的旧值
    16. {
    17. Date temp(*this); // 在实现时需要先将this保存一份,然后给this+1
    18. _day += 1;
    19. return temp; // 因为temp是临时对象,因此只能以值的方式返回,不能返回引用
    20. }
    21. private:
    22. int _year;
    23. int _month;
    24. int _day;
    25. };
    26. int main()
    27. {
    28. Date d;
    29. Date d1(2023, 9, 13);
    30. d = d1++; // d: 2023,9,13  d1:2023,9,14
    31. d = ++d1; // d: 2023,9,14  d1:2023,9,14
    32. return 0;
    33. }

    前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载,C++ 规定:后置++重载时多增加一个 int 类型的参数,但调用函数时该参数不用传递,编译器自动传递。前置返回的是引用后置返回的是


    六、日期类的实现

    1、Date.h

    1. // Date.h
    2. #pragma once
    3. #include
    4. #include
    5. #include
    6. using namespace std;
    7. class Date
    8. {
    9. public:
    10. // 获取某年某月的天数
    11. int GetMonthDay(int year, int month)
    12. {
    13. assert(month >= 1 && month <= 12);
    14. // 每月的天数(这个函数会被频繁调用,每次进来都要重新定义数组,所以将其定义为静态的)
    15. // 默认是平年
    16. static int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    17. int day = days[month];
    18. if (month == 2 &&((year % 4 == 0 && year % 100 != 0) || (year%400 == 0)))
    19. // 把month == 2写在前面可以直接筛选出更少的内容
    20. {
    21. day += 1; // 闰年的二月是29天
    22. }
    23. return day;
    24. }
    25. Date(int year = 1, int month = 1, int day = 1) // 全缺省的构造函数
    26. {
    27. _year = year;
    28. _month = month;
    29. _day = day;
    30. //判断日期是否合法
    31. if (_year < 0 || _month <= 0 || _month >= 13 || _day <= 0 || _day > GetMonthDay(_year, _month))
    32. {
    33. cout << _year << "/" << _month << "/" << _day << "->";
    34. cout << "非法日期" << endl;
    35. }
    36. }
    37. // 打印日期
    38. void Print()
    39. {
    40. cout << _year << "/" << _month << "/" << _day << endl;
    41. }
    42.    
    43.    // 拷贝构造、赋值运算符、析构函数用编译器自动生成的就可以了(因为Date类是浅拷贝)
    44.    
    45.    // 日期 += 天数 --> d1 += 100
    46. Date& operator+=(int day);
    47. // 日期 + 天数 --> d1 + 100
    48. Date operator+(int day);
    49. // 日期 -= 天数 --> d1 -= 100
    50. Date& operator-=(int day);
    51. // 日期 - 天数 --> d1 - 100
    52. Date operator-(int day);
    53.    // 前置++
    54. Date& operator++(); // 编译器会解释为:Date& operator++(Date* const this);
    55. // 后置++
    56. Date operator++(int); // 编译器会解释为:Date& operator++(Date* const this, int);
    57. // 前置--
    58. Date& operator--();
    59. // 后置--
    60. Date operator--(int);
    61. // >运算符重载
    62. bool operator>(const Date& d)
    63. {
    64. if (_year > d._year)
    65. return true;
    66. else if (_year == d._year && _month > d._month)
    67. return true;
    68. else if (_year == d._year && _month == d._month && _day > d._day)
    69. return true;
    70. else
    71. return false;
    72. }
    73.    // ==运算符重载
    74. bool operator==(const Date& d)
    75. {
    76. return _year == d._year && _month == d._month && _day == d._day;
    77. }
    78. // 这里我们只需要把>和==运算符重载了,下面的运算符都可以复用其代码了
    79. // >=运算符重载
    80. bool operator>=(const Date& d)
    81. {
    82. return *this > d || *this == d; // 复用operator>、operator==
    83. }
    84. // <运算符重载
    85. bool operator<(const Date& d)
    86. {
    87. return !(*this >= d); // 复用operator>=,再取反
    88. }
    89. // <=运算符重载
    90. bool operator<=(const Date& d)
    91. {
    92. return !(*this > d); // 复用operator>,再取反
    93. }
    94. // !=运算符重载
    95. bool operator!=(const Date& d)
    96. {
    97. return !(*this == d); // 复用operator==,再取反
    98. }
    99.    // 日期 - 日期(返回相差天数) --> d1 - d2
    100. int operator-(const Date& d);
    101. private:
    102. int _year;
    103. int _month;
    104. int _day;
    105. };

    2、Date.cpp

    (1)日期 += 天数(返回累加天数后的日期)

    比如:d1 += 100

    注意:d1本身要被更改,天数累加到 d1 上面去。

    1. Date& Date::operator+=(int day)
    2. {
    3. if (day < 0) // 如果day是负数,就向前计算,相当于 -=
    4. {
    5. return *this -= -day; // 调用-=运算符重载函数
    6. }
    7. _day += day; // 累加天数
    8. // 日期不合法,需要进位
    9. while (_day > GetDays(_year, _month)) // 表示当前月的天数已经过完了
    10. {
    11. _day -= GetDays(_year, _month); // 减去当前月的天数
    12. _month++; // 月进位
    13. if (_month == 13) // 判断当前月份是否合法
    14. {
    15. _year++; // 年进位
    16. _month = 1; // 更新为1月
    17. }
    18. }
    19. return *this;
    20. /* 写法二:复用+运算符重载函数的代码
    21. *this = *this + day; // d1等价于*this,对d1进行+天数操作,再赋值给d1
    22. return *this; // 返回d1
    23. */
    24. }

     (2)日期 + 天数(返回累加天数后的日期)

    比如 :d1 + 100

    注意:d1本身不能被更改,天数累加到一个临时对象上面去。

    1. // 写法一:
    2. Date Date::operator+(int day)
    3. {
    4. Date tmp(*this); // 拷贝构造一份临时对象,防止调用本函数的对象被更改
    5. tmp._day += day; // 累加天数
    6. while (tmp._day > GetDays(tmp._year, tmp._month)) // 表示当前月的天数已经过完了
    7. {
    8. tmp._day -= GetDays(tmp._year, tmp._month); // 减去当前月的天数
    9. tmp._month++; // 月进位
    10. if (tmp._month == 13) // 判断当前月份是否合法
    11. {
    12. tmp._year++; // 年进位
    13. tmp._month = 1; // 更新为1月
    14. }
    15. }
    16. return tmp; // 返回临时对象
    17. }
    18. // 写法二:
    19. Date Date::operator+(int day)
    20. {
    21. /* 复用 += 运算符重载函数的代码 */
    22. Date tmp(*this); // 拷贝构造一份临时对象
    23. tmp += day; // 对临时对象进行 += 天数操作
    24. return tmp; // 返回临时对象
    25. }

    (3)日期 -= 天数(返回累减天数后的日期)

    比如:d1 -= 100

    1. Date& Date::operator-=(int day)
    2. {
    3. if (day < 0) // 如果day小于0,就往后计算,相当于 +=
    4. {
    5. return *this += -day; // 调用+=运算符重载函数
    6. }
    7. _day -= day; // 累减天数
    8. while (_day <= 0) // 说明天数不够减了,需要向上一个月去借
    9. {
    10. _month--; // 月份-1
    11. if (_month == 0)
    12. {
    13. _year--;
    14. _month = 12;
    15. }
    16. _day += GetDays(_year, _month); // 借上一个月的天数
    17. }
    18. return *this;
    19. }

     (4)日期 - 天数(返回累减天数后的日期)

    比如:d1 - 100

    1. Date Date::operator-(int day)
    2. {
    3. // 复用 -= 运算符重载函数的代码
    4. Date tmp(*this); // 拷贝构造一份临时对象
    5. tmp -= day; // 对临时对象进行 -= 天数操作
    6. return tmp; // 返回临时对象
    7. }

     (5)前置++ 和 后置++

    注意:按正常的运算符重载规则,无法区分 前置++ 和 后置++,为了区分,这里做了一个特殊处理,给 后置++ 增加了一个 int 参数,这个参数仅仅是为了区分,使 前置++ 和 后置++ 构成重载。

    1. // 前置++
    2. // ++d1
    3. Date& Date::operator++()
    4. {
    5. // 复用 += 运算符重载函数的代码
    6. *this += 1;
    7. return *this;
    8. }
    9. // 后置++
    10. // d1++
    11. Date Date::operator++(int)
    12. {
    13. Date tmp(*this); // 保存当前对象自减前的值
    14. *this += 1; // 复用 += 运算符重载函数的代码
    15. return tmp; // 返回当前对象自减前的值
    16. }

    (6)前置-- 和 后置– 
    1. // 前置--
    2. // --d1
    3. Date& Date::operator--()
    4. {
    5. // 复用 -= 运算符重载函数的代码
    6. *this -= 1;
    7. return *this;
    8. }
    9. // 后置--
    10. // d1--
    11. Date Date::operator--(int)
    12. {
    13. Date tmp(*this); // 保存当前对象自减前的值
    14. *this -= 1; // 复用 -= 运算符重载函数的代码
    15. return tmp; // 返回当前对象自减前的值
    16. }

    (7)日期 - 日期(返回相差的天数,有正负之分)

    比如:d1 - d2 

    思路:让小的日期不断往后++,直到等于大的日期,统计加了多少次,就相差多少天。

    • 大的日期 - 小的日期 = 正的天数
    • 小的日期 - 大的日期 = 负的天数
    1. int Date::operator-(const Date& d)
    2. {
    3. // 判断出大的日期和小的日期
    4. Date max = *this;
    5. Date min = d;
    6. int flag = 1; // 加一个flag变量来控制天数的正负
    7. if (max < min)
    8. {
    9. max = d;
    10. min = *this;
    11. flag = -1;
    12. }
    13. // 让小的日期累加天数,加了多少次,说明就相差了多少天
    14. int count = 0;
    15. while (min != max)
    16. {
    17. ++min;
    18. ++count;
    19. }
    20. return flag * count;
    21. }

    【总结】 
    1. // Date.cpp
    2. #include "Date.h"
    3. // 日期 += 天数
    4. Date& Date::operator+=(int day)
    5. {
    6. if (day < 0) // 如果day是负数,就向前计算,相当于 -=
    7. {
    8. return *this -= -day; // 调用-=运算符重载函数
    9. }
    10. _day += day; // 累加天数
    11. // 日期不合法,需要进位
    12. while (_day > GetDays(_year, _month)) // 表示当前月的天数已经过完了
    13. {
    14. _day -= GetDays(_year, _month); // 减去当前月的天数
    15. _month++; // 月进位
    16. if (_month == 13) // 判断当前月份是否合法
    17. {
    18. _year++; // 年进位
    19. _month = 1; // 更新为1月
    20. }
    21. }
    22. return *this;
    23. }
    24. // 日期 + 天数
    25. Date Date::operator+(int day)
    26. {
    27. Date tmp(*this); // 拷贝构造一份临时对象,防止调用本函数的对象被更改
    28. tmp._day += day; // 累加天数
    29. while (tmp._day > GetDays(tmp._year, tmp._month)) // 表示当前月的天数已经过完了
    30. {
    31. tmp._day -= GetDays(tmp._year, tmp._month); // 减去当前月的天数
    32. tmp._month++; // 月进位
    33. if (tmp._month == 13) // 判断当前月份是否合法
    34. {
    35. tmp._year++; // 年进位
    36. tmp._month = 1; // 更新为1月
    37. }
    38. }
    39. return tmp; // 返回临时对象
    40. }
    41. // 日期 -= 天数
    42. Date& Date::operator-=(int day)
    43. {
    44. if (day < 0) // 如果day小于0,就往后计算,相当于 +=
    45. {
    46. return *this += -day; // 调用+=运算符重载函数
    47. }
    48. _day -= day; // 累减天数
    49. while (_day <= 0) // 说明天数不够减了,需要向上一个月去借
    50. {
    51. _month--; // 月份-1
    52. if (_month == 0)
    53. {
    54. _year--;
    55. _month = 12;
    56. }
    57. _day += GetDays(_year, _month); // 借上一个月的天数
    58. }
    59. return *this;
    60. }
    61. // 日期 -= 天数
    62. Date Date::operator-(int day)
    63. {
    64. // 复用 -= 运算符重载函数的代码
    65. Date tmp(*this); // 拷贝构造一份临时对象
    66. tmp -= day; // 对临时对象进行 -= 天数操作
    67. return tmp; // 返回临时对象
    68. }
    69. // 前置++
    70. Date& Date::operator++()
    71. {
    72. // 复用 += 运算符重载函数的代码
    73. *this += 1;
    74. return *this;
    75. }
    76. // 后置++
    77. Date Date::operator++(int)
    78. {
    79. Date tmp(*this); // 保存当前对象自减前的值
    80. *this += 1; // 复用 += 运算符重载函数的代码
    81. return tmp; // 返回当前对象自减前的值
    82. }
    83. // 前置--
    84. Date& Date::operator--()
    85. {
    86. // 复用 -= 运算符重载函数的代码
    87. *this -= 1;
    88. return *this;
    89. }
    90. // 后置--
    91. Date Date::operator--(int)
    92. {
    93. Date tmp(*this); // 保存当前对象自减前的值
    94. *this -= 1; // 复用 -= 运算符重载函数的代码
    95. return tmp; // 返回当前对象自减前的值
    96. }
    97. // 日期 - 日期
    98. int Date::operator-(const Date& d)
    99. {
    100. // 判断出大的日期和小的日期
    101. Date max = *this;
    102. Date min = d;
    103. int flag = 1; // 加一个flag变量来控制天数的正负
    104. if (max < min)
    105. {
    106. max = d;
    107. min = *this;
    108. flag = -1;
    109. }
    110. // 让小的日期累加天数,加了多少次,说明就相差了多少天
    111. int count = 0;
    112. while (min != max)
    113. {
    114. ++min;
    115. ++count;
    116. }
    117. return flag * count;
    118. }

    七、const 成员

    将 const 修饰的 “ 成员函数 ” 称之为 const 成员函数,const 修饰类成员函数,实际修饰该成员函数 隐含的 this 指针 ,表明在该成员函数中不能对类的任何成员进行修改。

    1. class Date
    2. {
    3. public:
    4. Date(int year, int month, int day)
    5. {
    6. _year = year;
    7. _month = month;
    8. _day = day;
    9. }
    10. void Print() // void Print(Date* const this)
    11. {
    12. cout << "Print()" << endl;
    13. cout << "year:" << _year << endl;
    14. cout << "month:" << _month << endl;
    15. cout << "day:" << _day << endl << endl;
    16. }
    17. void Print() const // void Print(const Date* const this)
    18. {
    19. cout << "Print() const" << endl;
    20. cout << "year:" << _year << endl;
    21. cout << "month:" << _month << endl;
    22. cout << "day:" << _day << endl << endl;
    23. }
    24. private:
    25. int _year; // 年
    26. int _month; // 月
    27. int _day; // 日
    28. };
    29. void Test()
    30. {
    31. Date d1(2022,1,1);
    32. d1.Print();
    33. const Date d2(2023,1,1); // const修饰
    34. d2.Print(); // d2.Print(&d2); // &d2的类型是const Date*,只能读不能写
    35. // 传给第一个Print会导致权限放大为可读可写
    36. }
    1. const 修饰成员函数是有好处的,这样 const 对象可以调用,非 const 对象也可以调用。
    2. 但并不是说所有的成员函数都要加 const ,具体得看成员函数的功能,如果成员函数是修改型(比如:operrato+=、Push),那就不能加;如果是只读型(比如:Print、operator+),那就最好加上 const。
    3. const 成员(只读)函数内不可以调用其它的非 const 成员(可读可写)函数(权限放大),非 const 成员(可读可写)函数内可以调用其它的 const 成员(只读)函数(权限缩小)。

    八、取地址及const取地址操作符重载

    下面这两个是默认成员函数,一般不用重新定义,不写编译器默认会自动生成。
    1. class Date
    2. {
    3. public:
    4. Date* operator&()// Date* operator&(Date* const this)
    5. {
    6. return this;
    7. }
    8. const Date* operator&()const // const Date* operator&(const Date* const this)
    9. {
    10. return this;
    11. }
    12. private:
    13. int _year; // 年
    14. int _month; // 月
    15. int _day; // 日
    16. };
    这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如不想让别人获取到这个类型对象的地址
    1. class Date {
    2. public:
    3. Date* operator&()
    4. {
    5. return nullptr;
    6. }
    7. const Date* operator&() const
    8. {
    9. return nullptr;
    10. }
    11. private:
    12. int _year;
    13. int _month;
    14. int _day;
    15. };
  • 相关阅读:
    程序化广告平台如何让app广告变现收益最大化?
    四周(28天)的个人开发总结(技巧)
    JavaScript之JS事件机制
    网络-HTTPS
    jsbarcode生成条码
    前端SVG的学习
    three.js工厂点击动画、标签
    Android 多平台AR SDK 集成使用
    【英语:发音基础】A6.基础词汇-核心形容词
    Springboot毕设项目基于javaweb电费管理系统v39ge(java+VUE+Mybatis+Maven+Mysql)
  • 原文地址:https://blog.csdn.net/weixin_74531333/article/details/132829986