【C++】类和对象(三)

简介: 类和对象(三)拷贝构造函数:当我们想要将一个已确定的类变量的值拷贝给另外一个相同类型的类变量,有什么快捷的方法吗?

类和对象(三)

拷贝构造函数

当我们想要将一个已确定的类变量的值拷贝给另外一个相同类型的类变量,有什么快捷的方法吗?

就相当于定义了一个int类型的i=10,想将i复制给一个刚初始化的遍历j,int j=i;

这里我们就可以用到拷贝构造函数,以下我们来解释一下拷贝构造函数!!!

拷贝构造函数的写法:

class 类名 {
public:
  类名(const 类名& 变量名)
  {
  }
};

拷贝构造函数的特征:

  • 拷贝构造函数是一种特殊的构造函数,是构造函数的重载
  • 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用。

拷贝构造函数如何定义?拷贝构造函数的参数如何设置?:

拷贝构造函数的参数直接传类的变量?传值调用?

这里报错了?为什么呢,直接函数传值 为什么会报错呢

这里编译器编译不过去的,因为编译器认为这里会无限递归,编译器的警告是不允许参数的类型是类

这是为什么呢?我们先来理解一个例子,再回来看它!

此时我们有两个类,一个是日期类,应该是栈类,除了栈类中的a是指向动态开辟的空间,其他都是int类型

class date
{//日期类
public:
  int year;
  int month;
  int day;
};
class stack
{//栈类
public:
  int* a;
  int top;
  int capacity;
};

当我们为这两个类写其的拷贝构造函数用的是传值调用的情况下:

日期类是没有问题,因为编译器会为内置类型拷贝遍历创建临时变量

而栈类中top和capacity都是内置类型没有问题,主要是a这个变量,a是一个指向开辟在堆区的数组

假设st1和st2都是由st这个对象通过拷贝构造函数(传值调用)拷贝出来的,拷贝的时候会连指向空间的那个指针一起拷贝出来,也就是拷贝出来会变成st1和st2两个变量的a都指向同一块空间,这样会造成很严重的错误(进栈和free的时候)


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

时,则拷贝构造函数是一定要写的,否则就是浅拷贝。

在C++中,函数调用如果是传值调用都是需要创建一个临时变量,将值拷贝一份给这个临时变量,而将值拷贝一份本身就是一个拷贝构造函数,因此就会死循环,造成无穷递归。

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

浅拷贝就是编译器自己会完成的,就一个内置类型按字节大小拷贝变量

字节序拷贝会如果变量是一个指向开辟在堆区的数组的指针,拷贝的不只有那个数组,还有其中的数据和指向这个数组的指针

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

义类型是调用其拷贝构造函数完成拷贝的。

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

我们最好在参数加个const修饰,这样可以防止权限放大

Date(const Date& d)
  {
    _year = d._year;
    _month = d._month;
    _day = d._day;
  }
int main()
{
    Date d1;//如果这里加个Const修饰,而上面参数没有用const修饰
    Date d2(d1);
}

权限只能缩小不能放大

当d1被const修饰后,就不能可以被修改,当参数没有const的时候,权限就会放大,就会造成错误。

运算符重载:

运算符重载的语法:

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

运算符重载的注意点:

  • 不能通过连接其他符号来创建新的操作符:比如operator@
  • 重载操作符必须有一个类类型参数
  • 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this
  • .* :: sizeof ?: . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现。
bool operator==(const Date& d)
  {//日期类
    return _year == d._year &&
      _month == d._month &&
        _day == d._day;
  }


<<(流插入)的优先级比==高,因此下面这个语句会报错

cout << d1 == d2 << endl;

赋值运算符重载

赋值运算符重载格式

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

返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值

检测是否自己给自己赋值

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


//赋值运算符的重载
  Date& operator=(const Date &d)//这里可以不需要用&,不会无穷递归
  {
    if (this != &d)
    {//解决自己给自己赋值的问题
      _year = d._year;
      _month = d._month;
      _day = d._day;
    }
    //解决连续赋值的问题
    return *this;
  }

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

// 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
Date& operator=(Date& left, const Date& right)
{
if (&left != &right)
{
left._year = right._year;
left._month = right._month;
left._day = right._day;
}
return left;
}
// 编译失败:
// error C2801: “operator =”必须是非静态成员

原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现

一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值

运算符重载只能是类的成员函数。

用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。

注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符

重载完成赋值。

前置++和后置++的运算符重载:

前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载

C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递

Date& Date::operator++()

前置++:返回+1之后的结果

注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率

注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存

const成员函数:

class A
{
public:
  void Print()const
  {
    cout << _a << endl;
  }
private:
  int _a = 10;
};
int main()
{
  const A aa;//加const会报错,权限扩大了
  aa.Print();//*this
  return 0;
}

将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数

隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。

请思考下面的几个问题:

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

1.不可以

2.可以

3.不可以

4.可以

注意:权限只能缩小,不能扩大

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

这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需

要重载,比如想让别人获取到指定的内容!

class A
{
public:
  void Print()const
  {
    cout << _a << endl;
  }
  A* operator&()
  {
    return this;
  }
  const A* operator&()const
  {
    return this;
  }
private:
  int _a = 10;
};
int main()
{
  const A aa;//加const会报错,权限扩大了
  aa.Print();//*this
  cout << &aa << endl;
  return 0;
}

日期类:

Date.h文件:

#pragma once
#pragma once
#include<iostream>
#include<cassert>
using namespace std;
class Date {
  friend istream& operator>>(istream& in, Date& d);
  friend ostream& operator<<(ostream& out,const Date&d);
public:
  Date(int year = 1900, int month = 1, int day = 1);
  void Print()const;
  int GetMonthDay(int year, int month)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;
  bool operator>=(const Date& d)const;
  Date& operator+=(int day);
  Date operator+(int day)const;
  Date& operator-=(int day);
  Date operator-(int day) const;
  int operator-( const Date& d) ;
  Date& operator++();//++d1
  Date operator++(int);//d1++
  Date& operator--();//--d1
  Date operator--(int);//d1--
private:
  int _year;
  int _month;
  int _day;
};
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);

Date.cpp文件:

#pragma once
#include"Date.h"
int Date::GetMonthDay(int year, int month)const
{
  assert(month > 0 && month < 13);
  int monthArray[13] = { 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 monthArray[month];
  }
}
Date::Date(int year, int month, int day)
{
  //_year = year;
  //_month = month;
  //_day = day;
  //检查是否合法
  if (month > 0 && month < 13 && day <= GetMonthDay(year, month))
  {
    _year = year;
    _month = month;
    _day = day;
  }
  else
  {
    cout << "日期非法" << endl;
  }
}
void Date::Print()const
{
  cout << _year << '/' << _month << '/' << _day << endl;
}
bool Date:: operator==(const Date& d)const
{//这里我们的成员是共有的,如果私有怎么解决呢?
  //那我们直接放在类里面,这里报错说:参数太多,
  //类里面的函数会有一个隐藏的参数将其中一个参数删了就好了
  return _year == d._year &&
    _month == d._month &&
    _day == d._day;
}
bool Date::operator<(const Date& d)const
{
  return _year < d._year
    || (_year == d._year && _month < d._month)
    || (_year == d._year && _month == d._month && _day < d._day);
}
Date Date::operator+(int day)const
{
  Date tmp(*this);
  tmp += day;
  return tmp;
}
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)
    {
      ++_year;
      _month = 1;
    }
  }
  return *this;
}
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)
  {
    *this += -day;
    return *this;
  }
  _day -= day;
  while (_day <= 0)
  {
    --_month;
    if (_month == 0)
    {
      _year--;
      _month = 12;
    }
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}
Date Date:: operator-(int day)const
{
  Date tmp(*this);
  tmp -= day;
  return tmp;
}
int Date::operator-(const Date& d)
{
  Date max = *this;
  Date min = d;
  int flag = 1;
  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }
  return n * flag;
}
bool Date:: operator!=(const Date& d)const
{
  if (*this == d)return false;
  return true;
}
Date& Date::operator++()
{//++d1
  *this += 1;
  return *this;
}
Date Date::operator++(int)
{//d1++
  Date tmp(*this);
  *this += 1;
  return tmp;
}
Date& Date:: operator--()//--d1
{
  *this -= 1;
  return *this;
}
Date Date::operator--(int)//d1--
{//效率低一些
  Date tmp(*this);
  *this -= 1;
  return tmp;
}
ostream& operator<<(ostream& out,const Date&d)
{//全局函数不能访问私有
  cout << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  return out;
}
istream& operator>>(istream& in, Date& d)
{
  in >> d._year >> d._month >> d._day;
  return in;
}
s;
}
Date Date::operator++(int)
{//d1++
  Date tmp(*this);
  *this += 1;
  return tmp;
}
Date& Date:: operator--()//--d1
{
  *this -= 1;
  return *this;
}
Date Date::operator--(int)//d1--
{//效率低一些
  Date tmp(*this);
  *this -= 1;
  return tmp;
}
ostream& operator<<(ostream& out,const Date&d)
{//全局函数不能访问私有
  cout << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  return out;
}
istream& operator>>(istream& in, Date& d)
{
  in >> d._year >> d._month >> d._day;
  return in;
}
相关文章
|
5天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
19 0
|
5天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
3天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
3天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
8天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
9天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”
|
10天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
|
29天前
|
存储 C++ 容器
C++入门指南:string类文档详细解析(非常经典,建议收藏)
C++入门指南:string类文档详细解析(非常经典,建议收藏)
38 0
|
29天前
|
存储 编译器 C语言
C++入门: 类和对象笔记总结(上)
C++入门: 类和对象笔记总结(上)
34 0