【C++初阶】类和对象(中)

【C++初阶】类和对象(中)

🥕个人主页:开敲🍉

🔥所属专栏:C++🥭

🌼文章目录🌼

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

2. 构造函数

    2.1 构造函数概念

    2.2 构造函数的特性

3. 析构函数

    3.1 析构函数的概念

    3.2 析构函数的特性

4. 拷贝构造函数

    4.1 拷贝构造函数的概念

    4.2 拷贝构造函数的特性

5. 赋值运算符重载

    5.1 运算符重载

    5.2 赋值运算符重载

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

6. 日期类的实现

7. const成员

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

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

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

  那么空类真的顾名思义就是里面什么都没有吗?  非也,任何类在什么都不写时,系统会默认生成以下6个默认成员函数。

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

  class Data{};

2. 构造函数
    2.1 构造函数概念

  对于以下Date类:

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

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

    2.2 构造函数的特性

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

  其特征如下:

函数名与类名相同

无返回值

对象实例化时,编译器自动调用对应的构造函数

构造函数可以重载:

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

  如上图,很显然,一般情况下系统自动生成的构造函数无法满足我们的需求,因此构造函数一般是由我们自己定义的。

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

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

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

 无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。
注意:无参构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为
是默认构造函数。

3. 析构函数
    3.1 析构函数的概念

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

  析构函数:析构函数并不是对类中的变量进行销毁,而是对类中动态开辟的空间和空间中的资源进行销毁,比如:对malloc等动态开辟内存的函数所开辟的空间进行销毁。

    3.2 析构函数的特性

析构函数名是在类名前加上 ~ 符号

无参数、无返回值(连void 都不能写)

③ 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。注意:析构
函数不能重载

 对象生命周期结束时,C++编译系统系统自动调用析构函数

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

  从上图我们可以看到:Date类中我们并没有定义析构函数,而是系统自动创建了析构函数,而Date类中还有我们自定义的Time类型,因此系统会调用Time中定义的析构函数,如果没有,则还是调用Time中系统自动生成的析构函数

如果类中没有申请资源(动态开辟空间)时可以不写析构函数;如果有资源申请(动态开辟空间)时必须要自己定义析构函数,系统默认的析构函数没法完成释放,会导致内存泄漏

4. 拷贝构造函数
    4.1 拷贝构造函数的概念

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

  那在创建对象时,可否创建一个与已存在对象一模一样的新对象呢?这我们就要聊到拷贝构造函数了。

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

    4.2 拷贝构造函数的特性

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

拷贝构造函数是构造函数的一个重载形式

拷贝构造函数的参数只有一个且必须是类类型对象的引用,如果使用传值的方式传类类型的对象,则编译器会直接报错,因为会引发无穷递归的问题

  引发无穷递归的原因:传值会调用拷贝构造函数,形成套娃

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

  上图我们并没有自己定义拷贝构造函数,因此用的是系统默认的拷贝构造函数,那这个时候就有问题了:使用系统默认的拷贝构造函数好像也可以完成拷贝功能呀,没啥问题。

  这里我们就要回到上面浅拷贝的问题上了,来看下面一段代码:

  这里我们并没有自己定义拷贝构造函数,而是使用了系统的默认构造函数对栈st2进行初始化,从结果上来看我们也确实是将栈st1中的每个元素都拷贝过来了,并且拿到了各自的栈顶元素。那么为什么程序会崩溃了呢?来看下面的图:

    所以,我上面红色字体的"各自的"是不对的,st1和st2指向了同一块空间,因此在拿取栈顶元素时也是在同一块空间内拿取。

  程序之所以会崩溃就是因为st1调用了一次析构函数,而st2又调用了一次析构函数,但是st1和st2指向的是同一块空间呀,对同一块空间释放两次显然是非法的,因此程序崩溃了。

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

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

  1. 使用已存在对象调用新对象

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

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

5. 赋值运算符重载
    5.1 运算符重载

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

  注意:

 不能通过连接其他符号来创建新的操作符:比如operator@

 重载操作符必须有一个类类型参数

 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义

 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐
藏的this

  .*   ::  sizeof   ?:   .   这五个运算符不能重载。

    5.2 赋值运算符重载

赋值运算符重载格式

  1. 参数类型:const Date&,传递引用可以提高效率

  2. 返回值类型:Date&,返回引用可以提高效率,有返回值是为了连续赋值

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

  4. 返回*this:要复合连续赋值的含义

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

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

 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。
意:
内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符
重载完成赋值。

class Time
{
public:
    void Change(int hour, int minute, int second)
    {
        _hour = hour;
        _minute = minute;
        _second = second;
    }

//运算符重载
    Time& operator=(Time& t)
    {
        if (this != &t)
        {
            _hour = t._hour;
            _minute = t._minute;
            _second = t._second;
        }
        return *this;
    }
    void Printf()
    {
        cout << _hour << ":" << _minute << ":" << _second << endl;
    }
private:
    int _hour;
    int _minute;
    int _second;
};


class Date
{
public:
    Date(int year, int month, int day)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    void Printf()
    {
        cout << _year << "-" << _month << "-" << _day << endl;
    }
    Time _t;
private:
    int _year;
    int _month;
    int _day;
};


int main()
{
    Date d1(2024, 7, 12);
    Date d2(1, 1, 1);
    d2 = d1;
    d1.Printf();
    d2.Printf();
    d1._t.Change(1, 1, 1);
    d2._t.Change(2, 2, 2);
    d1._t = d2._t;
    d1._t.Printf();
    d2._t.Printf();
    return 0;
}

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

//Date.h头文件,用于对类和类主体的声明和定义

#pragma once


#include <iostream>
using namespace std;

class Date
{
public:

    //构造函数
    Date(int year, int month, int day);

    //打印
    void Printf();

    //拷贝构造
    Date(const Date& d);

    //前置++重载
    Date& operator++()
    {
        _day += 1;
        //先++后使用
        return *this;
    }

    //后置++重载
    Date operator++(int)
    {

//先使用后++,因此需要保留++以前的值
        Date tmp = *this;
        _day += 1;
        return tmp;
    }

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

//Date.cpp源文件,用于对重载函数等的定义

#define _CRT_SECURE_NO_WARNINGS 1


#include "Date.h"


//打印
void Date::Printf()
{
    cout << _year << "-" << _month << "-" << _day << endl;
}

//构造函数
Date::Date(int year, int month, int day)
{
    _year = year;
    _month = month;
    _day = day;
}

//拷贝构造
Date::Date(const Date& d)
{
    _year = d._year;
    _month = d._month;
    _day = d._day;
}

int main()
{
    Date d1(2024, 7, 13);
    Date d2 = d1;

    Date d3 = d1++;
    Date d4 = ++d2;

    d1.Printf();
    d2.Printf();
    d3.Printf();
    d4.Printf();
    return 0;
}

  上面代码运行结果:

  可以看到,对于不同的++重载,实现的功能是不同的。前置++:先++再使用;后置++:先使用再++。

6. 日期类的实现

//Date.h头文件

#pragma once


#include <iostream>
using namespace std;

class Date
{
public:

    //友元函数
    friend ostream& operator<<(ostream& out,const Date& d);

    friend istream& operator>>(istream& in, Date& d);

    friend bool TrueDate(const Date& d);

    //判断日期是否合法
    bool TrueDate(const Date& d);


    //构造函数
    Date(int year, int month, int day);

    //打印
    void Printf();

    //拷贝构造
    Date(const Date& d);

    //前置++重载
    Date& operator++()
    {
        _day += 1;
        //先++后使用
        return *this;
    }

    //后置++重载
    Date operator++(int)
    {
        Date tmp = *this;
        _day += 1;
        return tmp;
    }

    //>重载函数声明
    bool operator>(const Date& d);

    //=重载函数声明
    bool operator==(const Date& d);

    //!=重载函数声明
    bool operator!=(const Date& d);

    //<重载函数声明
    bool operator<(const Date& d);

    //>=重载函数声明
    bool operator>=(const Date& d);

    //<=重载函数声明
    bool operator<=(const Date& d);

    //日期+=天数
    Date& operator+=(int day);

    //日期-=天数
    Date& operator-=(int day);

    //日期+天数
    Date operator+(int day);


    //日期-天数
    Date operator-(int day);


    //日期-日期
    int operator-(const Date& d);

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

//Date.cpp源文件

#define _CRT_SECURE_NO_WARNINGS 1


#include "Date.h"


//打印
void Date::Printf()
{
    cout << _year << "-" << _month << "-" << _day << endl;
}

//构造函数
Date::Date(int year, int month, int day)
{
    _year = year;
    _month = month;
    _day = day;
}

//拷贝构造
Date::Date(const Date& d)
{
    _year = d._year;
    _month = d._month;
    _day = d._day;
}


//>重载函数定义
bool Date::operator>(const Date& d)
{
    if (_year > d._year)
    {
        return true;
    }
    else if (_year == d._year && _month > d._month)
    {
        return true;
    }
    else if (_year == d._year && _month == d._month && _day > d._day)
    {
        return true;
    }
    return false;
}


//=重载函数定义
bool Date::operator==(const Date& d)
{
    return _year == d._year && _month == d._month && _day == d._day;
}


//!=重载函数定义
bool Date::operator!=(const Date& d)
{
    return !(*this == d);
}

//<重载函数定义
bool Date::operator<(const Date& d)
{
    return !(*this > d || *this == d);
}


//>=重载函数定义
bool Date::operator>=(const Date& d)
{
    return !(*this < d);
}

//<=重载函数定义
bool Date::operator<=(const Date& d)
{
    return !(*this > d);
}

//获取月份天数
int GetMonthDay(int year, int month)
{
    int arr[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };
    if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
    {
        return 29;
    }
    return arr[month];
}


//日期+=天数
Date& Date::operator+=(int day)
{
    if (day < 0)
    {
        *this -= day;
        return *this;
    }
    _day += day;
    while (_day > GetMonthDay(_year, _month))
    {
        _day -= GetMonthDay(_year, _month);
        _month++;
        if (_month == 13)
        {
            _month = 1;
            _year++;
        }
    }
    return *this;
}

//日期-=天数
Date& Date::operator-=(int day)
{
    if (day < 0)
    {
        *this += -day;
        return *this;
    }
    _day -= day;
    while (_day <= 0)
    {
        _month--;
        if (!_month)
        {
            _month = 12;
            _year--;
        }
        _day += GetMonthDay(_year, _month);
    }
    return *this;
}


//日期+天数
Date Date::operator+(int day)
{
    Date tmp = *this;
    if (day < 0)
    {
        tmp -= -day;
        return tmp;
    }
    tmp += day;
    return tmp;
}


//日期-天数
Date Date::operator-(int day)
{
    Date tmp = *this;
    if (day < 0)
    {
        tmp += day;
        return tmp;
    }
    tmp -= day;
    return tmp;
}


//判断是否是合法日期
bool TrueDate(const Date& d)
{
    if (d._month >= 13 || d._month <= 0 || d._day > GetMonthDay(d._year,d._month) || d._day <= 0)
        return false;
    return true;
}


//流输出<<重载函数定义
ostream& operator<<(ostream& out,const Date& d)
{
    out << d._year << "/" << d._month << "/" << d._day<< endl;
    return out;
}

//流插入>>重载函数定义
istream& operator>>(istream& in, Date& d)
{
    while (1)
    {
        cout << "请输入年/月/日:";
        in >> d._year >> d._month >> d._day;
        if (!TrueDate(d))
        {
            cout << "输入日期非法,请重新输入!" << endl;
            d.Printf();
        }
        else
        {
            break;
        }
    }
    return in;
}


//日期-日期
int Date::operator-(const Date& d)
{
    int ans = 0;
    Date max = *this;
    Date min = d;
    int flag = 1;
    if (*this < d)
    {
        max = d;
        min = *this;
        flag = -1;
    }
    while (min != max)
    {
        min += 1;
        ans++;
    }
    return ans * flag;
}

 

//test.cpp源文件

#define _CRT_SECURE_NO_WARNINGS 1

#include "Date.h"

int main()
{
    Date d1(1, 1, 1);
    cin >> d1;
    //Date d1(2024, 7, 13);
    Date d2 = d1;
    Date d3 = d1;
    Date d4 = d1;
    Date d5 = d1;

    d2 += -30000;
    d3 -= 30000;
    d4 = d1 + 100;
    d5 = d1 - 100;
    //d1.Printf();
    d2.Printf();
    d3.Printf();
    //d4.Printf();
    //d5.Printf();

    //d1<<cout;
    //cout << d1 << "\n" << d2 << endl;
    //d1.Printf();

    //int day = d3 - d1;
    //cout << day << endl;
    //Date d3 = ++d1;
    //bool ret1 = d2 < d3;
    //bool ret2 = d2 > d1;
    //bool ret3 = d3 == d1;

    //bool ret4 = d1 >= d3;

    //bool ret5 = d2 <= d1;

    //bool ret6 = d1 >= d2;
    //if (ret1)
    //    cout << "true" << endl;
    //else
    //    cout << "false" << endl;
    //if (ret2)
    //    cout << "true" << endl;
    //else
    //    cout << "false" << endl;
    //if (ret3)
    //    cout << "true" << endl;
    //else
    //    cout << "false" << endl;
    //if (ret4)
    //    cout << "true" << endl;
    //else
    //    cout << "false" << endl;
    //if (ret5)
    //    cout << "true" << endl;
    //else
    //    cout << "false" << endl;
    //if (ret6)
    //    cout << "true" << endl;
    //else
    //    cout << "false" << endl;

    return 0;
}

7. const成员

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

  

  来看下面一段代码:

  这里我们创建类d1和类d2,d2我们前面用const修饰了,这实际上是怎么修饰的呢?如下:

Date1(Date* const d);

  因此我们不能调用d2的Printf函数,因为这会导致权限放大

  下面思考以下几个问题:

 const对象可以调用非const成员函数吗?

 非const对象可以调用const成员函数吗?

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

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

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

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

class Date
{
    public :
    Date* operator&()
     {
         return this ;
     }
         const Date* operator&()const
     {
         return this ;
     }

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

 

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

                                             创作不易,点个赞呗,蟹蟹啦~

  • 24
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值