【C++打怪之路Lv4】-- 类和对象(中)

简介: 【C++打怪之路Lv4】-- 类和对象(中)

类的6个默认成员函数


1、特殊成员函数

2、不写编译器会自动生成


构造函数


概念

构造函数是初始化对象不是开空间

C语言中没有初始化,会出现随机值

六个特性

  1. 函数名与类名相同
  2. 无返回值
  3. 对象实例化 自动调用 该函数
  4. 构造函数可以重载
  5. 如没有显式定义的构造函数,编译器自动生成(隐式的无参构造函数);反之,则不会自动生成

注:①不显式写默认构造,对于内置类型成员变量,看编译器是否处理; 对于自定义类型成员变量才会调用它的 无参构造(不传参就可以调用的那个构造)

②默认构造函数包括:无参构造函数、全缺省构造函数、编译器默认生成的构造函数(隐式的无参构造函数)


6、内置类型成员变量在类中声明时可以给默认值

默认构造函数的意义

在两个栈实现一个队列,编译器给了初始化(在某种情况下有意义)


析构函数


概念

对象销毁时自动调用析构函数,完成对象中的资源清理

C语言没有写Destroy,会造成内存泄漏

四个特性

  1. 析构函数名在类名前加~
  2. 无参数无返回值
  3. 一个类只能析构一个函数,析构函数不能重载
  4. 在生命周期结束时自动调用
  • 析构函数内置类型不做处理自定义类型调用它的析构
  • 析构函数可以显式写

小结

  1. 有资源清理(开空间)才需要析构函数;如Stack、Queue
  2. 有两种场景不需要显式析构,用默认生成的就OK了
  • ①没有资源清理,如Date
  • ②内置类型成员没有资源需要清理,剩下的都是自定义类型成员;如MyQueue


拷贝构造函数


概念

用同类型的对象拷贝初始化

三个特性

  1. 拷贝构造函数是构造函数的一个重载形式
  2. 拷贝构造函数的参数只有一个且必须是类类对象的引用,使用传值方式编译器直接报错,会引发无穷递归
  3. 未显式定义,编译器会默认生成拷贝构造函数

总结

  1. 一般情况下,不需要显式写析构函数,就不用写拷贝构造函数(值拷贝)
  2. 如果 内部有指针 或者 一些值指向资源,需要显式写析构函数释放,需要写构造完成深拷贝; 如Satck、Queue、List


赋值运算符重载


运算符重载

相等操作符重载函数(比较Date中的两个对象是否相等)

在全局中

全局中operator== 函数,要屏蔽 Date类 中private

那封装性如何保证?友元 重载成员函数 解决

这里讲的是重载成员函数,把 内置类型成员 公有,这样在全局中函数就能 访问 内置类型成员

在类中

注意点

在主函数中

this 和 *this 的区别

赋值运算符重载

赋值运算符重载格式

注意点

赋值运算符重载 和 拷贝构造函数 的区别

传值返回 和 传引用返回 的区别

传值返回 会生成当前对象的一个拷贝,拷贝一个临时对象

引用返回 生成某别名,出了作用域就销毁了

总结 虽然引用返回减少了拷贝,但出了函数作用域,返回对象还在才能用引用(在静态)

前置++ 和 后置++ 重载


const成员


含义

const修饰的是*this,本质上是改变this的类型

在哪用

  1. 运算符重载
  2. 不改变自身


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


不显式实现,编译器默认生成


日期类的实现


Date.h

#pragma once
 
#include<iostream>
#include<stdlib.h>
using namespace std;
 
class Date
{
  // 友元函数,可以访问私有
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
 
public:
  // 构造函数
  Date(int year, int month, int day);
 
  // 打印
  void Print();
 
  // 运算符重载
  // 实现</>,==就可以了,其他的复用(要建立栈帧,内联,不能声明和定义分离,在类里面定义就是内联)
  bool operator==(const Date& d) const;
  bool operator!=(const Date& d) const;
  bool operator>(const Date& d) const;
  bool operator>=(const Date& d) const;
  bool operator<(const Date& d) const;
  bool operator<=(const Date& d) const;
 
  static int GetMonthDay(int year, int month)
  {
    int GetMonthDayArr[] = { 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;
    }
    else return GetMonthDayArr[month];
  }
 
  // 检查日期是否正确
  bool checkDate()
  {
    if (_month < 1 || _month > 12 || _day <= 0 || _day > GetMonthDay(_year, _month)) return false;
    else return true;
  }
 
  // 日期 + 天数
  Date& operator+=(int day);
  Date operator+(int day) const;
 
  // 日期 - 天数
  Date& operator-=(int day);
  Date operator-(int day) const;
 
  // 前置++
  Date& operator++();
  // 后置++
  Date operator++(int) const;
 
  // 前置--
  Date& operator--();
  // 后置--
  Date operator--(int) const;
 
  // d1 - d2
  int operator-(const Date& d) const;
 
private:
  int _year;
  int _month;
  int _day;
};
 
// 流插入重载
ostream& operator<<(ostream& out, const Date& d);
// 流提取重载
istream& operator>>(istream& in, Date& d);

Date.cpp

#define _CRT_SECURE_NO_WARNINGS 1
 
#define _CRT_SECURE_NO_WARNINGS 1
 
#include"Date.h"
 
Date::Date(int year, int month, int day)
{
  //cout << "Date(int year, int month, int day)" << endl;
 
  _year = year;
  _month = month;
  _day = day;
}
 
void Date::Print()
{
  cout << _year << "-" << _month << "-" << _day << endl;
}
 
bool Date::operator==(const Date& d) const
{
  return  this->_year == d._year
    && this->_month == d._month
    && this->_day == d._day;
}
 
bool Date::operator!=(const Date& d) const
{
  return !(*this == d);
}
 
bool Date::operator>(const Date& d) const
{
  if (this->_year > d._year) return true;
  else if (this->_year == d._year && this->_month > d._month) return true;
  else if (this->_year == d._year && this->_month == d._month && this->_day > d._day) return true;
  return false;
}
 
bool Date::operator>=(const Date& d) const
{
  return *this > d || *this == d;
}
 
bool Date::operator<(const Date& d) const
{
  return !(*this >= d);
}
 
bool Date::operator<=(const Date& d) const
{
  return !(*this > d);
}
 
// 日期 + 天数
Date& Date::operator+=(int day)
{
  if (day < 0) return *this -= -day;
 
  _day += day;
  while (_day > GetMonthDay(_year, _month))
  {
    _day -= GetMonthDay(_year, _month);
    ++_month;
    if (_month == 13)
    {
      ++_year;
      _month = 1;
    }
  }
  return *this;
}
 
Date Date::operator+(int day) const
{
  Date tmp = *this;
  tmp += day;
 
  return tmp;
}
 
Date& Date::operator-=(int day)
{
  if (day < 0) return *this += -day;
 
  _day -= day;
  while (_day <= 0)
  {
    --_month;
    if (_month == 0)
    {
      _month = 12;
      --_year;
    }
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}
 
Date Date::operator-(int day) const
{
  Date tmp = *this;
  tmp -= day;
  return tmp;
}
 
// 前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
 
// 后置++
Date Date::operator++(int) const
{
  Date tmp = *this;
  tmp += 1;
  return tmp;
}
 
// 前置--
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}
 
// 后置--
Date Date::operator--(int) const
{
  Date tmp = *this;
  tmp -= 1;
  return tmp;
}
 
int Date::operator-(const Date& d) const
{
  Date max = *this;
  Date min = d;
  int n = 0, flag = 1;
  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;
  }
 
  while (min != max)
  {
    ++min;
    ++n;
  }
 
  return flag * n;
}
 
//ostream& Date::operator<<(ostream& out)
//{
//  out << _year << "-" << _month << "-" << _day << endl;
//  return out;
//}
 
ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year << "-" << d._month << "-" << d._day << endl;
  return out;
}
 
istream& operator>>(istream& in, Date& d)
{
  cout << "请输入年、月、日:";
  in >> d._year >> d._month >> d._day;
  if (!d.checkDate()) {
    cout << "输入的日期无效,请重新输入。" << endl;
    in.clear(); // 清除错误标志
    in.ignore(numeric_limits<streamsize>::max(), '\n'); // 忽略错误输入直到下一个换行符
    return in;
  }
  return in;
}

Test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
 
#include"Date.h"
void test1()
{
  Date d1(2024, 9, 26);
  Date d2(2024, 9, 26);
  bool ret1 = d1 > d2;
  bool ret2 = d1 >= d2;
  bool ret3 = d1 < d2;
  bool ret4 = d1 <= d2;
  bool ret5 = d1 == d2;
  bool ret6 = d1 != d2;
 
  cout << ret1 << endl;
  cout << ret2 << endl;
  cout << ret3 << endl;
  cout << ret4 << endl;
  cout << ret5 << endl;
  cout << ret6 << endl;
}
 
void test2()
{
  Date d1(2024, 9, 26);
  Date d2(2024, 9, 26);
 
  // += // 11-15
  Date tmp = d1 -= -100;
  d1.Print();
  //tmp.Print();
   + 
  //Date tmp2 = d2 + 50;
  //d2.Print();   // 9-26
  //tmp2.Print(); // 11-15
 
  //Date d3(2024, 9, 26);
  //Date d4(2024, 9, 26);
 
   -= //8-7
  //Date tmp3 = d3 -= 50;
  //d3.Print();
  //tmp3.Print();
   - 
  //Date tmp4 = d4 - 50;
  //d4.Print();
  //tmp4.Print();
}
 
void test3()
{
  Date d1(2024, 9, 26);
  Date d2(2024, 9, 26);
 
  Date tmp = --d1;
  d1.Print();
  tmp.Print();
 
  Date tmp2 = d2--;
  d2.Print();
  tmp2.Print();
}
 
void test4()
{
  Date d1(2024, 9, 26);
  Date d2(2024, 10, 1);
  int ret = d1 - d2;
  cout << ret << endl;
}
 
void test5()
{
  // 流插入和流提取 / 内置类型 直接用,为什么?
  //cout << "1";
  //printf("2");
  //cout << "3";
  //printf("4");
 
  Date d1(2024, 9, 26);
  //d1 << cout; // 类中
  cout << d1;   // 全局
}
 
void test6()
{
  Date d1(2024,9,27);
  Date d2(2024,10,1);
  cin >> d1 >> d2;
  cout << d1 << d2;
}
 
void test7()
{
  const Date d1(2024, 9, 27);
  Date d2(2024, 9, 27);
 
  bool d3 = d1 > d2;
  Date d4 = d1 - 10;
}
 
int main()
{
  //test1();
  //test2();
  //test3();
  //test4();
  //test5();
  //test6();
  test7();
}
目录
打赏
0
4
4
0
17
分享
相关文章
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
【C++篇】深度解析类与对象(中)
在上一篇博客中,我们学习了C++类与对象的基础内容。这一次,我们将深入探讨C++类的关键特性,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载、以及取地址运算符的重载。这些内容是理解面向对象编程的关键,也帮助我们更好地掌握C++内存管理的细节和编码的高级技巧。
【C++篇】深度解析类与对象(上)
在C++中,类和对象是面向对象编程的基础组成部分。通过类,程序员可以对现实世界的实体进行模拟和抽象。类的基本概念包括成员变量、成员函数、访问控制等。本篇博客将介绍C++类与对象的基础知识,为后续学习打下良好的基础。
|
1月前
|
【C++面向对象——类与对象】Computer类(头歌实践教学平台习题)【合集】
声明一个简单的Computer类,含有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,以及两个公有成员函数run、stop。只能在类的内部访问。这是一种数据隐藏的机制,用于保护类的数据不被外部随意修改。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。成员可以在派生类(继承该类的子类)中访问。成员,在类的外部不能直接访问。可以在类的外部直接访问。为了完成本关任务,你需要掌握。
70 19
【C++面向对象——类与对象】CPU类(头歌实践教学平台习题)【合集】
声明一个CPU类,包含等级(rank)、频率(frequency)、电压(voltage)等属性,以及两个公有成员函数run、stop。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。​ 相关知识 类的声明和使用。 类的声明和对象的声明。 构造函数和析构函数的执行。 一、类的声明和使用 1.类的声明基础 在C++中,类是创建对象的蓝图。类的声明定义了类的成员,包括数据成员(变量)和成员函数(方法)。一个简单的类声明示例如下: classMyClass{ public: int
53 13
【C++面向对象——继承与派生】派生类的应用(头歌实践教学平台习题)【合集】
本实验旨在学习类的继承关系、不同继承方式下的访问控制及利用虚基类解决二义性问题。主要内容包括: 1. **类的继承关系基础概念**:介绍继承的定义及声明派生类的语法。 2. **不同继承方式下对基类成员的访问控制**:详细说明`public`、`private`和`protected`继承方式对基类成员的访问权限影响。 3. **利用虚基类解决二义性问题**:解释多继承中可能出现的二义性及其解决方案——虚基类。 实验任务要求从`people`类派生出`student`、`teacher`、`graduate`和`TA`类,添加特定属性并测试这些类的功能。最终通过创建教师和助教实例,验证代码
55 5
【C++面向对象——群体类和群体数据的组织】实现含排序功能的数组类(头歌实践教学平台习题)【合集】
1. **相关排序和查找算法的原理**:介绍直接插入排序、直接选择排序、冒泡排序和顺序查找的基本原理及其实现代码。 2. **C++ 类与成员函数的定义**:讲解如何定义`Array`类,包括类的声明和实现,以及成员函数的定义与调用。 3. **数组作为类的成员变量的处理**:探讨内存管理和正确访问数组元素的方法,确保在类中正确使用动态分配的数组。 4. **函数参数传递与返回值处理**:解释排序和查找函数的参数传递方式及返回值处理,确保函数功能正确实现。 通过掌握这些知识,可以顺利地将排序和查找算法封装到`Array`类中,并进行测试验证。编程要求是在右侧编辑器补充代码以实现三种排序算法
43 5
【C++面向对象——类的多态性与虚函数】计算图像面积(头歌实践教学平台习题)【合集】
本任务要求设计一个矩形类、圆形类和图形基类,计算并输出相应图形面积。相关知识点包括纯虚函数和抽象类的使用。 **目录:** - 任务描述 - 相关知识 - 纯虚函数 - 特点 - 使用场景 - 作用 - 注意事项 - 相关概念对比 - 抽象类的使用 - 定义与概念 - 使用场景 - 编程要求 - 测试说明 - 通关代码 - 测试结果 **任务概述:** 1. **图形基类(Shape)**:包含纯虚函数 `void PrintArea()`。 2. **矩形类(Rectangle)**:继承 Shape 类,重写 `Print
49 4
【C++面向对象——类的多态性与虚函数】编写教学游戏:认识动物(头歌实践教学平台习题)【合集】
本项目旨在通过C++编程实现一个教学游戏,帮助小朋友认识动物。程序设计了一个动物园场景,包含Dog、Bird和Frog三种动物。每个动物都有move和shout行为,用于展示其特征。游戏随机挑选10个动物,前5个供学习,后5个用于测试。使用虚函数和多态实现不同动物的行为,确保代码灵活扩展。此外,通过typeid获取对象类型,并利用strstr辅助判断类型。相关头文件如&lt;string&gt;、&lt;cstdlib&gt;等确保程序正常运行。最终,根据小朋友的回答计算得分,提供互动学习体验。 - **任务描述**:编写教学游戏,随机挑选10个动物进行展示与测试。 - **类设计**:基类
35 3
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等