• 【C++类和对象中:解锁面向对象编程的奇妙世界】


    【本节目标】

    • 1. 类的6个默认成员函数

    • 2. 构造函数

    • 3. 析构函数

    • 4. 拷贝构造函数

    • 5. 赋值运算符重载

    • 6. const成员函数

    • 7. 取地址及const取地址操作符重载

    1.类的6个默认成员函数

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

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

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

    class Date {};

    2. 构造函数

    2.1 概念

    对于以下Date类

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. void Init(int year, int month, int day)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. void Print()
    13. {
    14. cout << _year << "-" << _month << "-" << _day << endl;
    15. }
    16. private:
    17. int _year;
    18. int _month;
    19. int _day;
    20. };
    21. int main()
    22. {
    23. Date d1;
    24. d1.Init(2022, 7, 5);
    25. d1.Print();
    26. Date d2;
    27. d2.Init(2022, 7, 6);
    28. d2.Print();
    29. return 0;
    30. }

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

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

    2.2 特性

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

    其特征如下:

    • 1. 函数名与类名相同。
    • 2. 无返回值。
    • 3. 对象实例化时编译器自动调用对应的构造函数。
    • 4. 构造函数可以重载。
    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, int month, int day)
    13. {
    14. _year = year;
    15. _month = month;
    16. _day = day;
    17. }
    18. // 3.重载写法:但是和上面的无参调用存在歧义,不能和1写法同时存在
    19. Date(int year = 1, int month = 1, int day = 1)
    20. {
    21. _year = year;
    22. _month = month;
    23. _day = day;
    24. }
    25. private:
    26. int _year;
    27. int _month;
    28. int _day;
    29. };
    30. void TestDate()
    31. {
    32. Date d1; // 调用无参构造函数
    33. Date d2(2015, 1, 1); // 调用带参的构造函数
    34. // 注意:如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明
    35. // 以下代码的函数:声明了d3函数,该函数无参,返回一个日期类型的对象
    36. // warning C4930: “Date d3(void)”: 未调用原型函数(是否是有意用变量定义的?)
    37. Date d3();
    38. }

    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. private:
    18. int _year;
    19. int _month;
    20. int _day;
    21. };
    22. int main()
    23. {
    24. // 将Date类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数
    25. // 将Date类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再生成
    26. // 无参构造函数,放开后报错:error C2512: “Date”: 没有合适的默认构造函数可用
    27. Date d1;
    28. return 0;
    29. }

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

            解答:C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的数据类 型,如:int/char...,自定义类型就是我们使用class/struct/union等自己定义的类型,看看下面的程序,就会发现编译器生成默认的构造函数会对自定类型成员_t调用的它的默认成员函数。

    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 中针对内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在0.类中声明时可以给默认值。

    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. // C++11支持,但是此时仍然是声明,此时没有对象
    21. // 声明时给了缺省值
    22. int _year = 1970;
    23. int _month = 1;
    24. int _day = 1;
    25. // 自定义类型
    26. Time _t;
    27. };
    28. int main()
    29. {
    30. Date d;
    31. return 0;
    32. }

    总结:默认生成的构造函数,会处理自定义类型去调用其他的默认构造,而不处理内置类型。

    注:Data* p也是内置类型。

    7. 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。 注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数。可以不传参数就调用构造,都可叫默认构造。这三个函数只能存在一个,否则产生歧义。

    1. class Date
    2. {
    3. public:
    4. Date()
    5. {
    6. _year = 1900;
    7. _month = 1;
    8. _day = 1;
    9. }
    10. Date(int year = 1900, int month = 1, int day = 1)
    11. {
    12. _year = year;
    13. _month = month;
    14. _day = day;
    15. }
    16. private:
    17. int _year;
    18. int _month;
    19. int _day;
    20. };
    21. // 以下测试函数能通过编译吗?
    22. void Test()
    23. {
    24. Date d1;//此时无参,重载与无参出现歧义
    25. }

    编译不通过:

    总结:

    • 1.一般情况下,尽量自己写构造函数。
    • 2.成员内部都是自定义类型,或者声明给了缺省值,此时可以让编译器自己生成构造函数。
    • 3.内置类型都当作未处理,都是随机值。

    3.析构函数

    3.1 概念

    通过前面构造函数的学习,我们知道一个对象是怎么来的,那一个对象又是怎么没呢的?

    析构函数:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由 编译器完成的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。

    3.2 特性

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

    • 1. 析构函数名是在类名前加上字符 ~。
    • 2. 无参数无返回值类型。
    • 3. 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构函数不能重载
    • 4. 对象生命周期结束时,C++编译系统系统自动调用析构函数。
    1. typedef int DataType;
    2. class Stack
    3. {
    4. public:
    5. Stack(size_t capacity = 3)
    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. //相当于destroy函数
    24. ~Stack()
    25. {
    26. if (_array)
    27. {
    28. free(_array);
    29. _array = nullptr;
    30. _capacity = 0;
    31. _size = 0;
    32. }
    33. }
    34. private:
    35. DataType* _array;
    36. int _capacity;
    37. int _size;
    38. };
    39. void TestStack()
    40. {
    41. Stack s;
    42. s.Push(1);
    43. s.Push(2);
    44. }

    5. 关于编译器自动生成的析构函数,是否会完成一些事情呢?下面的程序我们会看到,编译器生成的默认析构函数,对自定类型成员调用它的析构函数。

    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. //默认生成的析构函数,行为和构造类型
    16. //内置类型成员不做处理
    17. //自定义类型成员会去调用它的析构
    18. private:
    19. // 基本类型(内置类型)
    20. int _year = 1970;
    21. int _month = 1;
    22. int _day = 1;
    23. // 自定义类型
    24. Time _t;
    25. };
    26. int main()
    27. {
    28. Date d;
    29. return 0;
    30. }

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

    4. 拷贝构造函数

    4.1 概念

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

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

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

    4.2 特征

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

    • 1. 拷贝构造函数是构造函数的一个重载形式。
    • 2. 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错, 因为会引发无穷递归调用。
    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. void Print()
    13. {
    14. cout << _year << "年" << _month << "月" << _day << "日";
    15. }
    16. private:
    17. int _year;
    18. int _month;
    19. int _day;
    20. };
    21. // 浅拷贝
    22. // 这里可以想象结构体传参,d1传d,传值拷贝
    23. // 这里参数可以写出指针或者引用
    24. void func(Date d)
    25. {
    26. d.Print();
    27. }
    28. int main()
    29. {
    30. Date d1;
    31. func(d1);
    32. return 0;
    33. }

    运行结果:

    上面的日期类传值拷贝没有问题,那能说明我们上面的特征结论时错误的嘛?我们来看一下栈类的情况。

    1. #include
    2. using namespace std;
    3. typedef int DataType;
    4. class Stack
    5. {
    6. public:
    7. Stack(int capacity = 3)
    8. {
    9. _array = (DataType*)malloc(sizeof(DataType) * capacity);
    10. if (NULL == _array)
    11. {
    12. perror("malloc申请空间失败!!!");
    13. return;
    14. }
    15. _capacity = capacity;
    16. _size = 0;
    17. }
    18. void Print()
    19. {
    20. //...
    21. }
    22. ~Stack()
    23. {
    24. if (_array)
    25. {
    26. free(_array);
    27. _array = nullptr;
    28. _capacity = 0;
    29. _size = 0;
    30. }
    31. }
    32. private:
    33. DataType* _array;
    34. int _capacity;
    35. int _size;
    36. };
    37. //栈这里也传值拷贝,可以吗???
    38. void func(Stack st)
    39. {
    40. st.Print();
    41. }
    42. int main()
    43. {
    44. Stack st1;
    45. func(st1);
    46. return 0;
    47. }

    这里我们就崩溃了,为什么???

    这是因为栈类除了单纯存储了普通数据_top和_capacity,还存储了一个指针_array,而C++有析构函数,传值拷贝后,指针就都指向了同一块空间,当st出了作用域,st对象就会调用析构函数去释放指针所指向的空间,然后st1又会再一次调用一次析构函数,此时就是对空指针进行释放,所以程序就报错了,所以C++传值拷贝是有风险的。而上面的日期类仅仅存储普通数据,所以上面的Date类没有问题,所以浅拷贝/值拷贝是有问题的,解决Stack类需要用到我们的深拷贝。

    规定:自定义类型的对象拷贝的时候,调用一个函数,这个函数就叫做拷贝构造。

    我们首先来看一下为什么拷贝构造函数参数必须类类型对象的引用,而不能是传值。

    调用这个函数的时候,d1作为参数先要传参,d1去调用了拷贝构造函数dd,此时dd作为参数又要传参,dd又要去调用拷贝函数构造......只要传入的参数是对象,参数本身就会自动调用拷贝构造函数。这样就是一个无穷递归。

    调用拷贝 -> 先传参(传值传参) -> 形成新的拷贝构造函数 -> ......

    所以这里我们就需要传引用/传地址解决。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. Date(Date& dd)
    13. {
    14. //这里依然是浅拷贝
    15. _year = dd._year;
    16. _month = dd._month;
    17. _day = dd._day;
    18. }
    19. void Print()
    20. {
    21. cout << _year << "年" << _month << "月" << _day << "日";
    22. }
    23. private:
    24. int _year;
    25. int _month;
    26. int _day;
    27. };
    28. // 浅拷贝
    29. // 这里可以想象结构体传参,d1传d,传值拷贝
    30. // 这里参数可以写出指针或者引用
    31. void func(Date d)
    32. {
    33. d.Print();
    34. }
    35. int main()
    36. {
    37. Date d1;
    38. func(d1);
    39. cout << "\n";
    40. Date d2(d1);
    41. func(d2);
    42. return 0;
    43. }

    C++规定:自定义类型对象传参拷贝时,必须调用拷贝构造。

    那我们的栈类还能这样写吗?

    1. Stack(Stack& stt)
    2. {
    3. _array = stt._array;
    4. _capacity = stt._capacity;
    5. _size = stt._size;
    6. }

    上面这种方法仍然是错误的,是浅拷贝,同样会调用两次析构函数。这里需要用到我们的深拷贝,思想是开辟一个资源一样大的空间,然后在把值拷贝过来。

    1. #include
    2. using namespace std;
    3. typedef int DataType;
    4. class Stack
    5. {
    6. public:
    7. Stack(int capacity = 3)
    8. {
    9. _array = (DataType*)malloc(sizeof(DataType) * capacity);
    10. if (NULL == _array)
    11. {
    12. perror("malloc申请空间失败!!!");
    13. return;
    14. }
    15. _capacity = capacity;
    16. _size = 0;
    17. }
    18. //Stack(Stack& s)
    19. //{
    20. // 下面这种方法仍然是错误的,是浅拷贝
    21. // _array = s._array;
    22. // _capacity = s._capacity;
    23. // _size = s._size;
    24. //}
    25. Stack(Stack& stt)
    26. {
    27. _array = (int*)malloc(sizeof(int) * stt._capacity);
    28. if (_array == nullptr)
    29. {
    30. perror("malloc fail");
    31. exit(-1);
    32. }
    33. memcpy(_array, stt._array, sizeof(int) * stt._size);
    34. _size = stt._size;
    35. _capacity = stt._capacity;
    36. }
    37. void Print()
    38. {
    39. //...
    40. }
    41. ~Stack()
    42. {
    43. if (_array)
    44. {
    45. free(_array);
    46. _array = NULL;
    47. _capacity = 0;
    48. _size = 0;
    49. }
    50. }
    51. private:
    52. DataType* _array;
    53. int _capacity;
    54. int _size;
    55. };
    56. void func(Stack st)
    57. {
    58. st.Print();
    59. }
    60. int main()
    61. {
    62. Stack st1;
    63. func(st1);
    64. Stack st2(st1);//构造一个st2对象,用st1初始化
    65. func(st2);
    66. return 0;
    67. }

    通过监视窗口我们可以看到st1对象和st2对象指向的是不同的空间,但是内容都是一样的,此时调用的析构函数释放的空间就是不用的。

    不知道我们有没有发现,上面的Date类就算没有拷贝构造函数,也是能正常运行的,这是因为拷贝构造函数时一个默认成员函数,对内置类型会完成值拷贝,而对自定义类型Stack需要调用它的拷贝构造函数,需要字节写拷贝函数。但是并不是所有的自定义类型都要写拷贝构造函数,比如下面的MyQueue类:

    1. #include
    2. using namespace std;
    3. typedef int DataType;
    4. class Stack
    5. {
    6. public:
    7. Stack(int capacity = 3)
    8. {
    9. _array = (DataType*)malloc(sizeof(DataType) * capacity);
    10. if (NULL == _array)
    11. {
    12. perror("malloc申请空间失败!!!");
    13. return;
    14. }
    15. _capacity = capacity;
    16. _size = 0;
    17. }
    18. //Stack(Stack& s)
    19. //{
    20. // 下面这种方法仍然是错误的,是浅拷贝
    21. // _array = s._array;
    22. // _capacity = s._capacity;
    23. // _size = s._size;
    24. //}
    25. Stack(Stack& stt)
    26. {
    27. _array = (int*)malloc(sizeof(int) * stt._capacity);
    28. if (_array == nullptr)
    29. {
    30. perror("malloc fail");
    31. exit(-1);
    32. }
    33. memcpy(_array, stt._array, sizeof(int) * stt._size);
    34. _size = stt._size;
    35. _capacity = stt._capacity;
    36. }
    37. void Print()
    38. {
    39. //...
    40. }
    41. ~Stack()
    42. {
    43. if (_array)
    44. {
    45. free(_array);
    46. _array = NULL;
    47. _capacity = 0;
    48. _size = 0;
    49. }
    50. }
    51. private:
    52. DataType* _array;
    53. int _capacity;
    54. int _size;
    55. };
    56. class MyQueue
    57. {
    58. Stack _pushst;
    59. Stack _popst;
    60. int _size;
    61. };
    62. int main()
    63. {
    64. MyQueue q1;
    65. MyQueue q2(q1);
    66. return 0;
    67. }

    运行结果:

    这里也完成了我们的深拷贝。Date和MyQueue默认生成的拷贝构造函数就i可以使用,对应内置类型成员完成值拷贝,对应自定义类型成员调用这个成员的拷贝构造。但是Stack类需要字节写拷贝构造函数,完成深拷贝。像我们的顺序表、链表和二叉树都需要深拷贝。

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

    1. #include
    2. using namespace std;
    3. class Time
    4. {
    5. public:
    6. Time()
    7. {
    8. _hour = 1;
    9. _minute = 1;
    10. _second = 1;
    11. }
    12. //为防止写反,这里加const
    13. Time(const Time& t)
    14. {
    15. _hour = t._hour;
    16. _minute = t._minute;
    17. _second = t._second;
    18. cout << "Time::Time(const Time&)" << endl;
    19. }
    20. private:
    21. int _hour;
    22. int _minute;
    23. int _second;
    24. };
    25. class Date
    26. {
    27. private:
    28. // 基本类型(内置类型)
    29. int _year = 1970;
    30. int _month = 1;
    31. int _day = 1;
    32. // 自定义类型
    33. Time _t;
    34. };
    35. int main()
    36. {
    37. Date d1;
    38. // 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
    39. // 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数
    40. Date d2(d1);
    41. return 0;
    42. }

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

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

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

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

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

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

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

    5.赋值运算符重载

    5.1 运算符重载

    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. private:
    11. int _year;
    12. int _month;
    13. int _day;
    14. };
    15. int main()
    16. {
    17. Date d1;
    18. Date d2(2023, 10, 24);
    19. int x = 1, y = 2;
    20. bool ret1 = x > y;
    21. bool ret2 = x == y;
    22. //内置类型对象可以直接用各种运算符,内置类型都是简单类型
    23. //那自定义类型呢?
    24. //这里可以想象一下结构体的比较
    25. d1 == d2;//error
    26. d1 > d2;//error
    27. return 0;
    28. }

    运行结果:

    这里需要想象一下结构体的比较,比较结构体是比较内部的成员,这里的类也是类似的。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. //private:
    13. int _year;
    14. int _month;
    15. int _day;
    16. };
    17. bool Geater(Date x1, Date x2)
    18. {
    19. if (x1._year > x2._year)
    20. return true;
    21. else if (x1._year == x2._year && x1._month > x2._month)
    22. return true;
    23. else if (x1._year == x2._year && x1._month == x2._month && x1._day > x2._day)
    24. return true;
    25. else
    26. return false;
    27. }
    28. bool Equal(Date x1, Date x2)
    29. {
    30. //成员私有不可访问
    31. //我们可以改一下上面的限制符private
    32. return x1._year == x2._year
    33. && x1._month == x2._month
    34. && x1._day == x2._day;
    35. }
    36. int main()
    37. {
    38. Date d1;
    39. Date d2(2023, 10, 24);
    40. cout << Geater(d1, d2) << endl;
    41. cout << Equal(d1, d2) << endl;
    42. return 0;
    43. }

    运行结果:

    C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其 返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

    函数名字为:关键字operator后面接需要重载的运算符符号。

    函数原型:返回值类型 operator操作符(参数列表)

    注意:

    • 不能通过连接其他符号来创建新的操作符:比如operator@
    • 重载操作符必须有一个类类型参数
    • 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能通过重载运算法改变其内置类型的运算规则含义
    • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
    • .* ::(域作用限定符) sizeof ?:(三目运算符) . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. //private:
    13. int _year;
    14. int _month;
    15. int _day;
    16. };
    17. //这里会调用拷贝构造,但其实没必要
    18. //我们直接取别名即可
    19. bool operator>(const Date& x1, const Date& x2)
    20. {
    21. if (x1._year > x2._year)
    22. return true;
    23. else if (x1._year == x2._year && x1._month > x2._month)
    24. return true;
    25. else if (x1._year == x2._year && x1._month == x2._month && x1._day > x2._day)
    26. return true;
    27. else
    28. return false;
    29. }
    30. //这里会调用拷贝构造
    31. bool operator==(const Date& x1, const Date& x2)
    32. {
    33. return x1._year == x2._year
    34. && x1._month == x2._month
    35. && x1._day == x2._day;
    36. }
    37. int main()
    38. {
    39. Date d1;
    40. Date d2(2023, 10, 24);
    41. cout << operator>(d1, d2) << endl;
    42. cout << operator==(d1, d2) << endl;
    43. //这里就可以直接写成内置类型比较的形式
    44. //由于流插入 << 优先级比 > 和 == 优先级高,所以这里需要加括号
    45. cout << (d1 > d2) << endl; //operator>(d1,d2)
    46. cout << (d1 == d2) << endl; //operator==(d1,d2)
    47. return 0;
    48. }

    这里需要分清运算符重载和函数重载之间的关系,它们之间没有任何关系

    • 运算符重载:自定义类型可以直接使用运算符
    • 函数重载:可以允许参数不同的同名函数

    但是这里会发现运算符重载成全局的就需要成员变量是公有的,那么问题来了,封装性如何保证? 这里其实可以将函数移入到Date类中。

    但是这里报错了为什么呢?编译器提示:error C2804: 二进制“operator >”的参数太多,因为类中含有一个隐藏的this参数

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. //这里隐藏了一个this参数
    13. // bool operator==(Date* this, const Date& d2)
    14. // 这里需要注意的是,左操作数是this,指向调用函数的对象
    15. bool operator>(const Date& x2)
    16. {
    17. if (_year > x2._year)
    18. return true;
    19. else if (_year == x2._year && _month > x2._month)
    20. return true;
    21. else if (_year == x2._year && _month == x2._month && _day > x2._day)
    22. return true;
    23. else
    24. return false;
    25. }
    26. //这里会调用拷贝构造
    27. bool operator==(const Date& x2)
    28. {
    29. return _year == x2._year
    30. && _month == x2._month
    31. && _day == x2._day;
    32. }
    33. private:
    34. int _year;
    35. int _month;
    36. int _day;
    37. };
    38. int main()
    39. {
    40. Date d1;
    41. Date d2(2023, 10, 24);
    42. cout << (d1 > d2) << endl; //d1.operator>(d2) ==> d1.operator>(&d1,d2)
    43. cout << (d1 == d2) << endl; //d1.operator==(d2) ==> d1.operator==(&d1,d2)
    44. return 0;
    45. }

    我们再来实现一下+运算符重载

    1. #include
    2. #include
    3. using namespace std;
    4. class Date
    5. {
    6. public:
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. int GetMonthDay(int year, int month)
    14. {
    15. assert(year >= 1 && month >= 1 && month <= 12);
    16. int MonthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    17. if (month == 2 && (year % 4 == 0 && year % 100 != 0)
    18. || (year % 400 == 0))
    19. return 29;
    20. return MonthArray[month];
    21. }
    22. //d1 + 100
    23. void operator+(int day)
    24. {
    25. _day += day;
    26. while (_day > GetMonthDay(_year, _month))
    27. {
    28. _day -= GetMonthDay(_year, _month);
    29. _month++;
    30. if (_month == 13)
    31. {
    32. _month = 1;
    33. _year++;
    34. }
    35. }
    36. return;
    37. }
    38. private:
    39. int _year;
    40. int _month;
    41. int _day;
    42. };
    43. int main()
    44. {
    45. Date d1;
    46. Date d2(2023, 10, 24);
    47. d2 + 50;
    48. return 0;
    49. }

    通过监视窗口观察我们实际上实现的是+=运算符重载,因为d2对象的内容被改变了,而+运算符重载不会改变对象的内容。

    d2 += 50;//这里不支持连续+=,因为日期不能+=日期

    要实现连等,我们需要接收返回值,所以上面的+=运算符重载是需要返回值的。

    1. #include
    2. #include
    3. using namespace std;
    4. class Date
    5. {
    6. public:
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. int GetMonthDay(int year, int month)
    14. {
    15. assert(year >= 1 && month >= 1 && month <= 12);
    16. int MonthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    17. if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
    18. return 29;
    19. return MonthArray[month];
    20. }
    21. //d1 += 100
    22. Date operator+=(int day)
    23. {
    24. _day += day;
    25. while (_day > GetMonthDay(_year, _month))
    26. {
    27. _day -= GetMonthDay(_year, _month);
    28. _month++;
    29. if (_month == 13)
    30. {
    31. _month = 1;
    32. _year++;
    33. }
    34. }
    35. return *this;
    36. }
    37. private:
    38. int _year;
    39. int _month;
    40. int _day;
    41. };
    42. int main()
    43. {
    44. Date d1;
    45. Date d2(2023, 10, 22);
    46. d2 += 50;//这里不支持连续+=
    47. int i = 0;
    48. // + 操作符有返回值
    49. int ret1 = i + 50;
    50. int j = 0;
    51. // += 操作符有返回值
    52. int ret2 = j += i += 50;
    53. return 0;
    54. }

    上面我们返回的*this仍然是值拷贝,但是*this就是d2,d2的生命周期是在main函数中的,所以上面的运算符重载的返回值可以使用引用。

    1. Date& operator+=(int day)
    2. {
    3. _day += day;
    4. while (_day > GetMonthDay(_year, _month))
    5. {
    6. _day -= GetMonthDay(_year, _month);
    7. _month++;
    8. if (_month == 13)
    9. {
    10. _month = 1;
    11. _year++;
    12. }
    13. }
    14. return *this;
    15. }

    现在我们再来写我们的+运算符重载,首先我们要知道+和+=的区别,+操作符是不改变自身的。

    1. #include
    2. #include
    3. using namespace std;
    4. class Date
    5. {
    6. public:
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. int GetMonthDay(int year, int month)
    14. {
    15. assert(year >= 1 && month >= 1 && month <= 12);
    16. int MonthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    17. if (month == 2 && (year % 4 == 0 && year % 100 != 0)
    18. || (year % 400 == 0))
    19. return 29;
    20. return MonthArray[month];
    21. }
    22. // d2 + 50
    23. Date& operator+(int day)
    24. {
    25. Date tmp(*this);//拷贝一份d1
    26. tmp._day += day;
    27. while (tmp._day > GetMonthDay(tmp._year, tmp._month))
    28. {
    29. tmp._day -= GetMonthDay(tmp._year, tmp._month);
    30. tmp._month++;
    31. if (tmp._month == 13)
    32. {
    33. tmp._month = 1;
    34. tmp._year++;
    35. }
    36. }
    37. return tmp;
    38. }
    39. private:
    40. int _year;
    41. int _month;
    42. int _day;
    43. };
    44. int main()
    45. {
    46. Date d1;
    47. Date d2(2023, 10, 22);
    48. Date ret = d2 + 50;
    49. return 0;
    50. }

    这样就实现了我们的+运算符重载对象之间互不影响。

    5.2 赋值运算符重载

    1. 赋值运算符重载格式

    • 参数类型:const T&,传递引用可以提高传参效率
    • 返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
    • 检测是否自己给自己赋值
    • 返回*this :要复合连续赋值的含义
    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. // d1 = d3
    13. void operator=(const Date& d)
    14. {
    15. _year = d._year;
    16. _month = d._month;
    17. _day = d._day;
    18. }
    19. void Print()
    20. {
    21. cout << _year << "年" << _month << "月" << _day << "日" << endl;
    22. }
    23. private:
    24. int _year;
    25. int _month;
    26. int _day;
    27. };
    28. int main()
    29. {
    30. Date d1;
    31. d1.Print();
    32. Date d2(2023, 10, 26);
    33. //一个已经存在的对象去拷贝初始化另一个对象
    34. Date d3(d2);//拷贝构造函数
    35. //两个已经存在的对象的拷贝
    36. d1 = d3;//赋值运算符重载
    37. d1.Print();
    38. }

    运行结果:

    如果我们想要连续赋值呢?很明显连等是错误的。因为我们上面写的函数是没有返回值的。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. // d1 = d3
    13. Date& operator=(const Date& d)
    14. {
    15. _year = d._year;
    16. _month = d._month;
    17. _day = d._day;
    18. return *this;
    19. }
    20. void Print()
    21. {
    22. cout << _year << "年" << _month << "月" << _day << "日" << endl;
    23. }
    24. private:
    25. int _year;
    26. int _month;
    27. int _day;
    28. };
    29. int main()
    30. {
    31. Date d1;
    32. d1.Print();
    33. Date d2(2023, 10, 26);
    34. //一个已经存在的对象去拷贝初始化另一个对象
    35. Date d3(d2);//拷贝构造函数
    36. //两个已经存在的对象的拷贝
    37. d1 = d3;//赋值运算符重载
    38. d1.Print();
    39. //连续赋值
    40. d2 = d1 = d3;
    41. }

    这样就实现了连等的操作。

    但是我们能对象给对象自己赋值,很明显是可以的。但是按照我们上面的代码太复杂,自己赋值自己就没必须再逐一拷贝。

    1. Date& operator=(const Date& d)//d是d1对象的别名,共用一块空间
    2. {
    3. if (this != &d)
    4. {
    5. _year = d._year;
    6. _month = d._month;
    7. _day = d._day;
    8. }
    9. return *this;
    10. }

    2. 赋值运算符只能重载成类的成员函数不能重载成全局函数

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 1900, int month = 1, int day = 1)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. int _year;
    13. int _month;
    14. int _day;
    15. };
    16. // 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
    17. Date& operator=(Date& left, const Date& right)
    18. {
    19. if (&left != &right)
    20. {
    21. left._year = right._year;
    22. left._month = right._month;
    23. left._day = right._day;
    24. }
    25. return left;
    26. }
    27. // 编译失败:
    28. // 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 = 1970;
    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. #include
    2. using namespace std;
    3. // 这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
    4. typedef int DataType;
    5. class Stack
    6. {
    7. public:
    8. Stack(size_t capacity = 10)
    9. {
    10. _array = (DataType*)malloc(capacity * sizeof(DataType));
    11. if (nullptr == _array)
    12. {
    13. perror("malloc申请空间失败");
    14. return;
    15. }
    16. _size = 0;
    17. _capacity = capacity;
    18. }
    19. void Push(const DataType& data)
    20. {
    21. // CheckCapacity();
    22. _array[_size] = data;
    23. _size++;
    24. }
    25. ~Stack()
    26. {
    27. if (_array)
    28. {
    29. free(_array);
    30. _array = nullptr;
    31. _capacity = 0;
    32. _size = 0;
    33. }
    34. }
    35. private:
    36. DataType* _array;
    37. size_t _size;
    38. size_t _capacity;
    39. };
    40. int main()
    41. {
    42. Stack s1;
    43. s1.Push(1);
    44. s1.Push(2);
    45. s1.Push(3);
    46. s1.Push(4);
    47. Stack s2;
    48. s2 = s1;
    49. return 0;
    50. }

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

    现在我们再来完善一下我们的日期类。当我们的输入的日期非法程序依然能够打印出来。

    注:当构造函数在声明和定义出现全缺省参数时,规定在声明的地方写全缺省参数,定义的地方不写。

    1. Date(int year = 1900, int month = 1, int day = 1)
    2. {
    3. _year = year;
    4. _month = month;
    5. _day = day;
    6. if (_year < 1 || _month < 1 || _month > 12
    7. || _day < 1 || _day > GetMonthDay(_year, _month))
    8. {
    9. assert(false);
    10. }
    11. }

    我们上面的运算符重载写了>运算符重载、=运算符重载和+=运算符重载。我们在来写一下!运算符重载等其他比较运算符重载,可以采用复用。

    1. bool operator>(const Date& x2)
    2. {
    3. if (_year > x2._year)
    4. return true;
    5. else if (_year == x2._year && _month > x2._month)
    6. return true;
    7. else if (_year == x2._year && _month == x2._month && _day > x2._day)
    8. return true;
    9. else
    10. return false;
    11. }
    12. bool operator==(const Date& x2)
    13. {
    14. return _year == x2._year
    15. && _month == x2._month
    16. && _day == x2._day;
    17. }
    18. bool operator!=(const Date& x2)
    19. {
    20. return !(*this == x2);
    21. }
    22. bool operator>=(const Date& x2)
    23. {
    24. return *this > x2 || *this == x2;
    25. }
    26. bool operator<(const Date& x2)
    27. {
    28. return !(*this >= x2);
    29. }

    我们再来看一下下面两种复用哪种更优?下面这个是+操作符重载复用+=操作符重载

    1. Date operator+=(int day)
    2. {
    3. //如果传入的day是负数
    4. if(day < 0)
    5. {
    6. return *this -= (-day);
    7. }
    8. _day += day;
    9. while (_day > GetMonthDay(_year, _month))
    10. {
    11. _day -= GetMonthDay(_year, _month);
    12. _month++;
    13. if (_month == 13)
    14. {
    15. _month = 1;
    16. _year++;
    17. }
    18. }
    19. return *this;
    20. }
    21. Date operator+(int day)
    22. {
    23. Date tmp(*this);
    24. tmp += day;
    25. return tmp;
    26. }

    这种是+=操作符重载复用+操作符重载的实现

    1. Date& operator=(const Date& d)
    2. {
    3. if (this != &d)
    4. {
    5. _year = d._year;
    6. _month = d._month;
    7. _day = d._day;
    8. }
    9. return *this;
    10. }
    11. Date operator+(int day)
    12. {
    13. Date tmp(*this);//拷贝一份d1
    14. tmp._day += day;
    15. while (tmp._day > GetMonthDay(tmp._year, tmp._month))
    16. {
    17. tmp._day -= GetMonthDay(tmp._year, tmp._month);
    18. tmp._month++;
    19. if (tmp._month == 13)
    20. {
    21. tmp._month = 1;
    22. tmp._year++;
    23. }
    24. }
    25. return tmp;
    26. }
    27. Date& operator+=(int day)
    28. {
    29. *this = *this + day;
    30. return *this;
    31. }

    上面的第一种写法+操作符重载复用+=操作符重载,+操作符重载进行了两次拷贝对象,而后面的那种写法+=操作符重载复用+操作符重载,+操作符重载进行了两次拷贝对象,+=操作符重载进行了两次拷贝对象,还有=操作符重载的一次。

    我们来实现一下-=操作符重载和-操作符重载,这里仍然是让-操作符重载复用-=操作符重载

    1. Date& operator-= (int day)
    2. {
    3. //如果传入的day是负数
    4. if(day < 0)
    5. {
    6. return *this += (-day);
    7. }
    8. _day -= day;
    9. while (_day <= 0)
    10. {
    11. _month--;
    12. if (_month == 0)
    13. {
    14. _year--;
    15. _month = 12;
    16. }
    17. _day += GetMonthDay(_year, _month);
    18. }
    19. return *this;
    20. }
    21. Date operator-(int day)
    22. {
    23. Date tmp = *this;
    24. tmp -= day;
    25. return tmp;
    26. }

    结果验证:

    5.3 前置++和后置++重载

    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. // 前置++:返回+1之后的结果
    11. // 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
    12. Date& operator++()
    13. {
    14. *this += 1;
    15. return *this;
    16. }
    17. // 后置++:
    18. // 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
    19. // C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器\
    20. 自动传递
    21. // 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存\
    22. 一份,然后给this + 1
    23. // 而temp是临时对象,因此只能以值的方式返回,不能返回引用
    24. Date operator++(int)
    25. {
    26. Date temp(*this);
    27. *this += 1;
    28. return temp;
    29. }
    30. Date& operator--()
    31. {
    32. *this -= 1;
    33. return *this;
    34. }
    35. Date operator--(int)
    36. {
    37. Date temp(*this);
    38. *this -= 1;
    39. return temp;
    40. }
    41. private:
    42. int _year;
    43. int _month;
    44. int _day;
    45. };
    46. int main()
    47. {
    48. Date d;
    49. Date d1(2023, 10, 27);
    50. d = d1++; // d: 2023,10,27 d1:2023,10,28
    51. d = ++d1; // d: 2023,10,29 d1:2023,10,29
    52. return 0;
    53. }

    5.4 日期相减重载

    1. // d1 - d2
    2. Date operator-(const Date& d)
    3. {
    4. //假设左大右小
    5. int flag = 1;
    6. Date max = *this;
    7. Date min = d;
    8. //假设错了,左小右大,此时相减就是负数
    9. if (*this < d)
    10. {
    11. max = d;
    12. min = *this;
    13. flag = -1;
    14. }
    15. int n = 0;
    16. while (min != max)
    17. {
    18. ++min;
    19. ++n;
    20. }
    21. return n * flag;
    22. }

    我们再来回顾一下我们上面的Print函数,每次该成员函数都要我们自己去实现,比较麻烦,我们可以通过运算符重载去实现打印,由于此时是自定义类型,所以可以通过重载流插入运算符实现。

    cout是ostream类型的对象,cin是istream类型的对象​​​​​​​

    内置类型可以支持流插入操作,是因为库里面已经实现过了。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. // 全缺省的构造函数
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. void operator << (ostream& out)//cout是ostream的对象
    14. {
    15. out << _year << "年" << _month << "月" << _day << "日";
    16. }
    17. private:
    18. int _year;
    19. int _month;
    20. int _day;
    21. };
    22. int main()
    23. {
    24. Date d1(2023, 11, 5);
    25. cout << d1;//报错,why??
    26. d1 << cout;//运行成功!!
    27. return 0;
    28. }

    运行结果:

    双操作数的运算符,第一个参数是左操作数,第二个操作数是右操作数,作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this,所以对于第二种写法,第一个参数是d1,第二个参数是cout,可以转化为d1.operator<<(&d1,cout),对于第一种写法参数就不匹配,所以报错。虽然第二种写法是正确的,但是看着不习惯,要想第一种此恶法正确,我们必须第一个参数设置为cout。因此对与该函数我们可以写成全局函数。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. // 全缺省的构造函数
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. //private://此时必须注释,否则全局函数访问不到该变量
    14. int _year;
    15. int _month;
    16. int _day;
    17. };
    18. void operator << (ostream& out,Date &d)//cout是ostream的对象
    19. {
    20. out << d._year << "年" << d._month << "月" << d._day << "日";
    21. }
    22. int main()
    23. {
    24. Date d1(2023, 11, 5);
    25. cout << d1;
    26. //d1 << cout;
    27. return 0;
    28. }

    ​​​​​​此时就转化成了operator<<(cout,d1),虽然上面我们确实通过将该函数放到全局变量中实现了我们的流插入操作符函数,但是使用该函数的时候我们必须要将类的成员变量设置公开,那么这样不就与封装性相悖吗?我们可以通过友元来解决。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. // 全缺省的构造函数
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. //友元函数
    14. friend void operator << (ostream& out,Date &d);//cout是ostream的对象
    15. private:
    16. int _year;
    17. int _month;
    18. int _day;
    19. };
    20. void operator << (ostream& out,Date &d)//cout是ostream的对象
    21. {
    22. out << d._year << "年" << d._month << "月" << d._day << "日";
    23. }
    24. int main()
    25. {
    26. Date d1(2023, 11, 5);
    27. cout << d1;
    28. //d1 << cout;
    29. return 0;
    30. }

    上面使用了友元函数,这里介绍一下,友元函数就是相当你有一个私人游泳池(相当于类的私有成员变量),然后你的非常要好朋友可以直接去你的私人游泳池游泳(访问私有变量),此时你不介意。我们的流插入操作符还可以支持连续使用,想要连续使用就必须设置一个返回值,所以我们要修改一下上面的代码

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. // 全缺省的构造函数
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. //友元函数
    14. friend ostream& operator << (ostream& out,const Date &d);//cout是ostream的对象
    15. private:
    16. int _year;
    17. int _month;
    18. int _day;
    19. };
    20. //流插入的内容d不会改变,可以加上const修饰
    21. ostream& operator << (ostream& out,const Date &d)//cout是ostream的对象
    22. {
    23. out << d._year << "年" << d._month << "月" << d._day << "日";
    24. return out;
    25. }
    26. int main()
    27. {
    28. Date d1(2023, 11, 5);
    29. Date d2;
    30. //赋值运算符顺序:从右往左
    31. //流插入运算符顺序:从左往右
    32. //由运算符的结合性决定
    33. //这里的返回值必须是cout
    34. cout << d1 << d2;
    35. return 0;
    36. }

    我们再来实现一下流提取运算符重载

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. // 全缺省的构造函数
    7. Date(int year = 1900, int month = 1, int day = 1)
    8. {
    9. _year = year;
    10. _month = month;
    11. _day = day;
    12. }
    13. //友元函数
    14. friend ostream& operator << (ostream& out,const Date &d);//cout是ostream的对象
    15. friend istream& operator >> (istream& in,Date &d);//cin是istream的对象
    16. private:
    17. int _year;
    18. int _month;
    19. int _day;
    20. };
    21. //流插入的内容d不会改变,可以加上const修饰
    22. ostream& operator << (ostream& out,const Date &d)//cout是ostream的对象
    23. {
    24. out << d._year << "年" << d._month << "月" << d._day << "日";
    25. return out;
    26. }
    27. //流插入的内容d会改变,不可以加上const修饰
    28. istream& operator >> (istream& in,Date &d)//cin是istream的对象
    29. {
    30. in >> d._year >> d._month >> d._day;
    31. return in;
    32. }
    33. int main()
    34. {
    35. Date d1(2023, 11, 5);
    36. Date d2;
    37. //赋值运算符顺序:从右往左
    38. //流插入运算符顺序:从左往右
    39. //由运算符的结合性决定
    40. //这里的返回值必须是cout
    41. cin >> d1 >> d2;
    42. cout << d1 << d2;
    43. return 0;
    44. }

    运行结果:

    总结:其他的运算符一般实现成成员函数,流插入和流提取操作符必须实现到全局中,这样才能让流对象作第一个参数。流本质是为了解决自定义类型输入和输出问题,C语言的printf函数只能指定内置类型,同时打印输出的时候还要指定输出格式,C语言的printf函数和scanf函数无法解决自定义类型的输入输出问题。C++通过面向对象和运算符重载来解决。

    6.日期类的实现

    1. class Date
    2. {
    3. public:
    4. // 获取某年某月的天数
    5. int GetMonthDay(int year, int month)
    6. {
    7. static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
    8. 31 };
    9. int day = days[month];
    10. if (month == 2
    11. && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
    12. {
    13. day += 1;
    14. }
    15. return day;
    16. }
    17. // 全缺省的构造函数
    18. Date(int year = 1900, int month = 1, int day = 1);
    19. // 拷贝构造函数
    20. // d2(d1)
    21. Date(const Date& d);
    22. // 赋值运算符重载
    23. // d2 = d3 -> d2.operator=(&d2, d3)
    24. Date& operator=(const Date& d);
    25. // 析构函数
    26. ~Date();
    27. // 日期+=天数
    28. Date& operator+=(int day);
    29. // 日期+天数
    30. Date operator+(int day);
    31. // 日期-天数
    32. Date operator-(int day);
    33. // 日期-=天数
    34. Date& operator-=(int day);
    35. // 前置++
    36. Date& operator++();
    37. // 后置++
    38. Date operator++(int);
    39. // 后置--
    40. Date operator--(int);
    41. // 前置--
    42. Date& operator--();
    43. // >运算符重载
    44. bool operator>(const Date& d);
    45. // ==运算符重载
    46. bool operator==(const Date& d);
    47. // >=运算符重载
    48. bool operator >= (const Date& d);
    49. // <运算符重载
    50. bool operator < (const Date& d);
    51. // <=运算符重载
    52. bool operator <= (const Date& d);
    53. // !=运算符重载
    54. bool operator != (const Date& d);
    55. // 日期-日期 返回天数
    56. int operator-(const Date& d);
    57. private:
    58. int _year;
    59. int _month;
    60. int _day;
    61. };

    7.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()
    11. {
    12. cout << "Print()" << endl;
    13. cout << "year:" << _year << endl;
    14. cout << "month:" << _month << endl;
    15. cout << "day:" << _day << endl << endl;
    16. }
    17. private:
    18. int _year; // 年
    19. int _month; // 月
    20. int _day; // 日
    21. };
    22. void Test()
    23. {
    24. Date d1(2022, 1, 13);
    25. d1.Print();
    26. const Date d2(2022, 1, 13);
    27. d2.Print();
    28. }
    29. int main()
    30. {
    31. Test();
    32. return 0;
    33. }

    当我们给对象加上const限制时,这里报错了为什么呢?

    作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this,这个隐藏的this类型的Date* cosnt this,而我们传入的类型时const Date* this。这里就会存在权限放大的问题,我们需要在隐藏的this类型的前面加上cosnt,但是this类型是隐藏的,我们应该怎么加呢?C++规定在函数之后写上cosnt就可以对隐藏的this类型的前面加上cosnt。

    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() const
    11. {
    12. cout << "Print()" << endl;
    13. cout << "year:" << _year << endl;
    14. cout << "month:" << _month << endl;
    15. cout << "day:" << _day << endl << endl;
    16. }
    17. private:
    18. int _year; // 年
    19. int _month; // 月
    20. int _day; // 日
    21. };
    22. void Test()
    23. {
    24. Date d1(2022, 1, 13);
    25. d1.Print();
    26. const Date d2(2022, 1, 13);
    27. d2.Print();
    28. }
    29. int main()
    30. {
    31. Test();
    32. return 0;
    33. }

    加上之后非const类型对象也能运行,因为只是进行了权限的缩小。运行结果:

    总结:类似于比较运算符,打印函数和+-运算符,不会修改任何成员,所以在写该类函数的时候我们可以加上const。成员函数定义的原则:1、能定义成cosnt的成员函数都应该定义成cosnt,这样const对象(权限平移)和非const对象(权限缩小)都可以调用。2、要修改成员变量的成员函数,不能定义成cosnt。3、流插入和流提取不能加上cosnt,它们不是成员函数,没有this指针,是全局函数。

    请思考下面的几个问题:

    1. const对象可以调用非const成员函数吗?不可以,权限不能放大

    2. 非const对象可以调用const成员函数吗?可以,权限可以缩小

    3. const成员函数内可以调用其它的非const成员函数吗?

    4. 非const成员函数内可以调用其它的const成员函数吗?

    8.取地址及const取地址操作符重载

    这两个默认成员函数一般不用重新定义 ,编译器默认会生成。

    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. Date* operator&()
    11. {
    12. cout << "Date * operator&()" << endl;
    13. return this;
    14. }
    15. const Date* operator&()const
    16. {
    17. cout << "const Date * operator&()const" << endl;
    18. return this;
    19. }
    20. private:
    21. int _year; // 年
    22. int _month; // 月
    23. int _day; // 日
    24. };
    25. int main()
    26. {
    27. Date d1;
    28. const Date d2;
    29. cout << &d1 << endl;
    30. cout << &d2 << endl;
    31. return 0;
    32. }

    运行结果:

    为什么这里要写两个取地址操作符重载呢?因为普通对象返回Date*,而const对象返回cosnt Date*,这两个是不同的,参数也是不同的,所以能构成重载。如果我们注释第一个非const成员函数。

    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. //Date* operator&()
    11. //{
    12. // cout << "Date * operator&()" << endl;
    13. // return this;
    14. //}
    15. const Date* operator&()const
    16. {
    17. cout << "const Date * operator&()const" << endl;
    18. return this;
    19. }
    20. private:
    21. int _year; // 年
    22. int _month; // 月
    23. int _day; // 日
    24. };
    25. int main()
    26. {
    27. Date d1;
    28. const Date d2;
    29. cout << &d1 << endl;
    30. cout << &d2 << endl;
    31. return 0;
    32. }

    运行结果:

    此时我们发现就会调用非cosnt成员函数,此时发生了参数和返回值权限的缩小。这个就和我们吃饭一样,有好吃的有自己相吃的就去吃,没有的就将就一下。

    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. //Date* operator&()
    11. //{
    12. // cout << "Date * operator&()" << endl;
    13. // return this;
    14. //}
    15. /*const Date* operator&()const
    16. {
    17. cout << "const Date * operator&()const" << endl;
    18. return this;
    19. }*/
    20. private:
    21. int _year; // 年
    22. int _month; // 月
    23. int _day; // 日
    24. };
    25. int main()
    26. {
    27. Date d1;
    28. const Date d2;
    29. cout << &d1 << endl;
    30. cout << &d2 << endl;
    31. return 0;
    32. }

    运行结果:

    这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需 要重载,比如想让别人获取到指定的内容!

    ​​​​​​​

  • 相关阅读:
    寒假训练——第三周(线性DP)
    C# 异步编程模式详解
    软件机器人助力企业产地证自动化申报,提高竞争力,降低成本
    关于额外的ht.ui插件如Carouse轮播组件,源码、js库文件、API接口文档、DEMO地址
    Ourphp建站系统存在SQL注入
    【android开发-10】android中四种布局详细介绍
    Matplotlib绘图-快速上手可视化工具
    vue组件 data选项
    Sample Average Approximation,SAA
    22款奔驰GLE450升级香氛负离子 清新淡雅
  • 原文地址:https://blog.csdn.net/qq_64446981/article/details/133964885