C++从入门到精通(第三篇) :类和对象(中篇)

@TOC
在这里插入图片描述

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

如果一个类中什么成员都没有,简称为空类。空类中什么都没有吗?并不是的,任何一个类在我们不写的情
况下,都会自动生成下面6个默认成员函数。
在这里插入图片描述

2. 构造函数

  • 在C语言数据结构时,创建结构变量我们经常需要自行调用结构初始化函数,否则可能会报错,为了避免忘记调用初始化函数,C++对此做出了优化,即在创建对象时自动调用初始化函数,也就是构造函数
  • 概念:

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

  • 特性:
  1. 函数名必须和类名一致

  2. 无返回值(没有返回值并不是void,void返回值是空)

  3. 对象实例化时编译器自动调用对应的构造函数(在C语言上的优化)

  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函数,该函数无参,返回一个日期类型的对象
Date d3();
}
  1. 如果类中没有显式定义构造函数(我们没有主动写),则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成
class Date
{
public:
    /*
    // 如果用户显式定义了构造函数,编译器将不再生成
    Date (int year, int month, int day)
    {
    _year = year;
    _month = month;
    _day = day;
    }
    */
private:
    int _year;
    int _month;
    int _day;
};
void Test()
{
    // 没有主动写构造函数,此处会调用编译器生成的默认构造函数
    Date d;
}
  1. 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个(默认构造函数:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数)
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;
}

在这里插入图片描述

编译器不能明确知道该调用哪一个,所以报错了

3.析构函数

  • 概念

析构函数不是完成对象的销毁,局部对象销毁工作是由编译器完成的,而对象在销毁时会自动调用析构函数,完成类的一些资源清理工作(释放动态开辟的空间)

  • 特性:
  1. 析构函数名是在类名前加上字符 ~

  2. 无参数无返回值

  3. 一个类有且只有一个析构函数,若未显式定义,系统会自动生成默认的析构函数(不能重载)

  4. 对象生命周期结束时,C++编译系统系统自动调用析构函数 (在C语言上的优化)

  • 例:
typedef int DataType;
class SeqList
{
public:
    SeqList(int capacity = 10)//构造函数
    {
        _pData = (DataType*)malloc(capacity * sizeof(DataType));
        assert(_pData);
        _size = 0;
        _capacity = capacity;
    }
    ~SeqList()//析构函数
    {
        cout << "~SeqList()" << endl;
        if (_pData)
        {
            free(_pData); // 释放堆上的空间
            _pData = NULL; // 将指针置为空
            _capacity = 0;
            _size = 0;
        }
    }
private:
    int* _pData;
    size_t _size;
    size_t _capacity;
};

int main()
{
    SeqList sl;
    return 0;
}

4.拷贝构造函数

  • 概念:

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

  • 特征
  1. 拷贝构造函数是构造函数的一个重载形式(参数不同)

    1. 拷贝构造函数的参数只有一个且必须使用引用传参,使用传值方式会引发无穷递归调用(传值也是一种拷贝,会继续调用拷贝函数)
  • 例:
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)//构造函数
    {
        _year = year;
        _month = month;
        _day = day;
    }
    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 Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    Date d1;
    // 这里d2调用的默认拷贝构造完成拷贝,d2和d1的值也是一样的。
    Date d2(d1);
    return 0;
}
  1. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,对于像日期类这样的类(只有指针类型的类)是没必要的,编译器生成的足够使用了,而对于存在指针类型的成员函数则会存现问题
class String
{
public:
    String(const char* str = "xxxx")
    {
        _str = (char*)malloc(strlen(str) + 1);
        strcpy(_str, str);
    }
    ~String()//析构函数,进行释放动态开辟的空间
    {
        cout << "~String()" << endl;
        free(_str);
    }
private:
    char* _str;
};
int main()
{
    String s1("hello");
    String s2(s1);
}

s1和s2中的 str 指向的是同一份空间 ,析构时会被 释放 两次 ,所以会报错

5.赋值运算符重载

运算符重载

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

  • 使用方法:
  1. 函数名字为:关键字operator后面接需要重载的运算符符号。
  2. 函数原型:返回值类型 operator操作符(参数列表)
  • 注意:
  1. 不能通过连接其他符号来创建新的操作符,如@等

  2. 重载操作符必须有一个类类型或者枚举类型的操作数

  3. .* 、:: 、sizeof 、?: 、. 注意以上5个运算符不能重载

  4. 如果重载函数在类外,想要访问类里的成员变量,有两种方式

  • 例:
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    // bool operator==(Date* this, const Date& d2)
    // 这里需要注意的是,左操作数是this指向的调用函数的对象
    bool operator==(const Date& d2)
    {
        return _year == d2._year
        && _month == d2._month
        && _day == d2._day;
    }
private:
    int _year;
    int _month;
    int _day;
};
void Test()
{
    Date d1(2018, 9, 26);
    Date d2(2018, 9, 27);
    cout << (d1 == d2) << endl;
}

赋值运算符重载

  • 例:
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    Date(const Date& d)
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
    Date& operator=(const Date& d)
    {
        if (this != &d)//避免对象赋值自己
        {
            _year = d._year;
            _month = d._month;
            _day = d._day;
        }
    }
private:
    int _year;
    int _month;
    int _day;
};

int main()
{
    Date d1(2022,2,1);//调用构造函数
    Date d2;
    d2=d1;//调用赋值操作符重载
    return 0;
}
  • 赋值运算符主要有四点:
  1. 参数类型

  2. 返回值

  3. 检测是否自己给自己赋值

  4. 返回*this

  5. 一个类如果没有显式定义赋值运算符重载,编译器也会生成一个,完成对象按字节序的值拷贝

6.日期类的实现

通过上面的知识,我们可以写出日期类的实现了

  • 接口的展示
    class Date
    {
    public:
      // 获取某年某月的天数
      int GetMonthDay(int year, int month);
      // 全缺省的构造函数
      Date(int year = 1900, int month = 1, int day = 1);
      // 拷贝构造函数
      // d2(d1)
      Date(const Date& d);
      // 赋值运算符重载
      // d2 = d3 -> d2.operator=(&d2, d3)
      Date& operator=(const Date& d);
      // 析构函数
      ~Date();
      // 日期+=天数
      Date& operator+=(int day);
      // 日期+天数
      Date operator+(int day);
      // 日期-天数
      Date operator-(int day);
      // 日期-=天数
      Date & operator-=(int day);
      // 前置++
      Date& operator++();
      // 后置++
      Date operator++(int);
      // 后置--
      Date operator--(int);
      // 前置--
      Date& operator--();
      // >运算符重载
      bool operator>(const Date& d);
      // ==运算符重载
      bool operator==(const Date& d);
      // >=运算符重载
      inline bool operator >= (const Date& d);
      // <运算符重载
      bool operator < (const Date& d);
      // <=运算符重载
      bool operator <= (const Date& d);
      // !=运算符重载
      bool operator != (const Date& d);
      // 日期-日期 返回天数
      int operator-(const Date& d);
    private:
      int _year;
      int _month;
      int _day;
    };
    
# 7.const成员
## const修饰类的成员函数

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

![在这里插入图片描述](https://uploadfiles.nowcoder.com/files/20220828/771287722_1661676095036/2408fdc40aac4754a73b2f4198a47344.png)
## 取地址及const取地址操作符重载

* 注:

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


```cpp
class Date
{
public:
    Date* operator&()
    {
        return this;
    }
    const Date* operator&()const
    {
        return this;
    }
private:
    int _year; // 年
    int _month; // 月
    int _day; // 日
};

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

  • 但此重载函数不常用,了解下就可以啦

请添加图片描述

看到这了,可以给博主点个免费的关注嘛b( ̄▽ ̄)d

#旷视面经##车好多##Java工程师实习#
全部评论
这都是核心内容啊
点赞 回复
分享
发布于 2022-08-30 13:54 陕西

相关推荐

3 3 评论
分享
牛客网
牛客企业服务