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

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

【C++类和对象中:解锁面向对象编程的奇妙世界】(一):https://developer.aliyun.com/article/1425447


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

Stack(Stack& stt)
{
  _array = stt._array; 
  _capacity = stt._capacity;
  _size = stt._size;
}


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

#include <iostream>
using namespace std;
typedef int DataType;
class Stack
{
public:
  Stack(int capacity = 3)
  {
    _array = (DataType*)malloc(sizeof(DataType) * capacity);
    if (NULL == _array)
    {
      perror("malloc申请空间失败!!!");
      return;
    }
    _capacity = capacity;
    _size = 0;
  }
  //Stack(Stack& s)
  //{
  //  下面这种方法仍然是错误的,是浅拷贝
  //  _array = s._array; 
  //  _capacity = s._capacity;
  //  _size = s._size;
  //}
  Stack(Stack& stt)
  {
    _array = (int*)malloc(sizeof(int) * stt._capacity);
    if (_array == nullptr)
    {
      perror("malloc fail");
      exit(-1);
    }
    memcpy(_array, stt._array, sizeof(int) * stt._size);
    _size = stt._size;
    _capacity = stt._capacity;
  }
  void Print()
  {
    //...
  }
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = NULL;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  int _capacity;
  int _size;
};
void  func(Stack st)
{
  st.Print();
}
int main()
{
  Stack st1;
  func(st1);
  Stack st2(st1);//构造一个st2对象,用st1初始化
  func(st2);
  return 0;
}


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


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

#include <iostream>
using namespace std;
typedef int DataType;
class Stack
{
public:
  Stack(int capacity = 3)
  {
    _array = (DataType*)malloc(sizeof(DataType) * capacity);
    if (NULL == _array)
    {
      perror("malloc申请空间失败!!!");
      return;
    }
    _capacity = capacity;
    _size = 0;
  }
  //Stack(Stack& s)
  //{
  //  下面这种方法仍然是错误的,是浅拷贝
  //  _array = s._array; 
  //  _capacity = s._capacity;
  //  _size = s._size;
  //}
  Stack(Stack& stt)
  {
    _array = (int*)malloc(sizeof(int) * stt._capacity);
    if (_array == nullptr)
    {
      perror("malloc fail");
      exit(-1);
    }
    memcpy(_array, stt._array, sizeof(int) * stt._size);
    _size = stt._size;
    _capacity = stt._capacity;
  }
  void Print()
  {
    //...
  }
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = NULL;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  int _capacity;
  int _size;
};
class MyQueue
{
  Stack _pushst;
  Stack _popst;
  int _size;
};
int main()
{
  MyQueue q1;
  MyQueue q2(q1);
  return 0;
}

运行结果:


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


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

#include <iostream>
using namespace std;
class Time
{
public:
  Time()
  {
    _hour = 1;
    _minute = 1;
    _second = 1;
  }
  //为防止写反,这里加const
  Time(const Time& t)
  {
    _hour = t._hour;
    _minute = t._minute;
    _second = t._second;
    cout << "Time::Time(const Time&)" << endl;
  }
private:
  int _hour;
  int _minute;
  int _second;
};
class Date
{
private:
  // 基本类型(内置类型)
  int _year = 1970;
  int _month = 1;
  int _day = 1;
  // 自定义类型
  Time _t;
};
int main()
{
  Date d1;
  // 用已经存在的d1拷贝构造d2,此处会调用Date类的拷贝构造函数
  // 但Date类并没有显式定义拷贝构造函数,则编译器会给Date类生成一个默认的拷贝构造函数
  Date d2(d1);
  return 0;
}

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


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

#include <iostream>
using namespace std;
// 这里会发现下面的程序会崩溃掉?这里就需要我们以后讲的深拷贝去解决。
typedef int DataType;
class Stack
{
public:
  Stack(size_t capacity = 10)
  {
    _array = (DataType*)malloc(capacity * sizeof(DataType));
    if (nullptr == _array)
    {
      perror("malloc申请空间失败");
      return;
    }
    _size = 0;
    _capacity = capacity;
  }
  void Push(const DataType& data)
  {
    // CheckCapacity();
    _array[_size] = data;
    _size++;
  }
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = nullptr;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  size_t _size;
  size_t _capacity;
};
int main()
{
  Stack s1;
  s1.Push(1);
  s1.Push(2);
  s1.Push(3);
  s1.Push(4);
  Stack s2(s1);
  return 0;
}


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


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

  • 使用已存在对象创建新对象
  • 函数参数类型为类类型对象
  • 函数返回值类型为类类型对象
#include <iostream>
using namespace std;
class Date
{
public:
  Date(int year, int minute, int day)
  {
    cout << "Date(int,int,int):" << this << endl;
  }
  Date(const Date& d)
  {
    cout << "Date(const Date& d):" << this << endl;
  }
  ~Date()
  {
    cout << "~Date():" << this << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
Date Test(Date d)
{
  Date temp(d);
  return temp;
}
int main()
{
  Date d1(2022, 1, 13);
  Test(d1);
  return 0;
}


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


5.赋值运算符重载


5.1 运算符重载


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;
    Date d2(2023, 10, 24);
    int x = 1, y = 2;
    bool ret1 = x > y;
    bool ret2 = x == y;
    //内置类型对象可以直接用各种运算符,内置类型都是简单类型
    //那自定义类型呢?
    //这里可以想象一下结构体的比较
    d1 == d2;//error
    d1 > d2;//error
    return 0;
}


运行结果:


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

#include <iostream>
using namespace std;
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;
};
bool Geater(Date x1, Date x2)
{
    if (x1._year > x2._year)
        return true;
    else if (x1._year == x2._year && x1._month > x2._month)
        return true;
    else if (x1._year == x2._year && x1._month == x2._month && x1._day > x2._day)
        return true;
    else
        return false;
}
bool Equal(Date x1, Date x2)
{
    //成员私有不可访问
    //我们可以改一下上面的限制符private
    return x1._year == x2._year
        && x1._month == x2._month
        && x1._day == x2._day;
}
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    cout << Geater(d1, d2) << endl;
    cout << Equal(d1, d2) << endl;
    return 0;
}


运行结果:


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


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


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


注意:

  • 不能通过连接其他符号来创建新的操作符:比如operator@
  • 重载操作符必须有一个类类型参数
  • 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能通过重载运算法改变其内置类型的运算规则含义
  • 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
  • .*::(域作用限定符) sizeof?:(三目运算符). 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
#include <iostream>
using namespace std;
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;
};
//这里会调用拷贝构造,但其实没必要
//我们直接取别名即可
bool operator>(const Date& x1, const Date& x2)
{
    if (x1._year > x2._year)
        return true;
    else if (x1._year == x2._year && x1._month > x2._month)
        return true;
    else if (x1._year == x2._year && x1._month == x2._month && x1._day > x2._day)
        return true;
    else
        return false;
}
//这里会调用拷贝构造
bool operator==(const Date& x1, const Date& x2)
{
    return x1._year == x2._year
        && x1._month == x2._month
        && x1._day == x2._day;
}
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    cout << operator>(d1, d2) << endl;
    cout << operator==(d1, d2) << endl;
    //这里就可以直接写成内置类型比较的形式
    //由于流插入 << 优先级比 > 和 == 优先级高,所以这里需要加括号
    cout << (d1 > d2) << endl; //operator>(d1,d2)
    cout << (d1 == d2) << endl; //operator==(d1,d2)
    return 0;
}


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

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


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


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

#include <iostream>
using namespace std;
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }
    //这里隐藏了一个this参数
    // bool operator==(Date* this, const Date& d2)
    // 这里需要注意的是,左操作数是this,指向调用函数的对象
    bool operator>(const Date& x2)
    {
        if (_year > x2._year)
            return true;
        else if (_year == x2._year && _month > x2._month)
            return true;
        else if (_year == x2._year && _month == x2._month && _day > x2._day)
            return true;
        else
            return false;
    }
    //这里会调用拷贝构造
    bool operator==(const Date& x2)
    {
        return _year == x2._year
            && _month == x2._month                                
            && _day == x2._day;
    }
private:
    int _year;
    int _month;
    int _day;
};
int main()
{
    Date d1;
    Date d2(2023, 10, 24);
    cout << (d1 > d2) << endl; //d1.operator>(d2) ==> d1.operator>(&d1,d2)
    cout << (d1 == d2) << endl; //d1.operator==(d2) ==> d1.operator==(&d1,d2)
    return 0;
}


【C++类和对象中:解锁面向对象编程的奇妙世界】(三):https://developer.aliyun.com/article/1425465

相关文章
|
23小时前
|
存储 编译器 C语言
从C语言到C++_11(string类的常用函数)力扣58和415(中)
从C语言到C++_11(string类的常用函数)力扣58和415
5 0
|
23小时前
|
存储 C语言 C++
从C语言到C++_11(string类的常用函数)力扣58和415(上)
从C语言到C++_11(string类的常用函数)力扣58和415
5 0
|
23小时前
|
C语言 C++
从C语言到C++⑧(第二章_类和对象_下篇_续)笔试选择题和OJ题
从C语言到C++⑧(第二章_类和对象_下篇_续)笔试选择题和OJ题
4 0
|
23小时前
|
Java 编译器 C语言
从C语言到C++⑦(第二章_类和对象_下篇)初始化列表+explicit+static成员+友元+内部类+匿名对象(下)
从C语言到C++⑦(第二章_类和对象_下篇)初始化列表+explicit+static成员+友元+内部类+匿名对象
6 0
|
1天前
|
算法 编译器 C语言
从C语言到C++⑥(第二章_类和对象_中篇_续)大练习(日期类)+笔试选择题(上)
从C语言到C++⑥(第二章_类和对象_中篇_续)大练习(日期类)+笔试选择题
7 3
|
1天前
|
编译器 C语言 C++
从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)(下)
从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)
4 1
|
1天前
|
存储 编译器 程序员
从C语言到C++④(第二章_类和对象_上篇)->类->封装->this指针(下)
从C语言到C++④(第二章_类和对象_上篇)->类->封装->this指针
4 0
|
1天前
|
C++
C++程序对象动态建立和释放
C++程序对象动态建立和释放
8 1
|
1天前
|
C++
【C++基础】类class
【C++基础】类class
9 1
|
1天前
|
安全 程序员 编译器
C++程序中的基类与派生类转换
C++程序中的基类与派生类转换
8 1