【c++】类和对象4

简介: 【c++】类和对象4

日期类的拓展

c语言中的printf函数只能打印内置类型,为了弥补这一不足,c++利用运算符重载可以打印自定义类型。

void operator<<(ostream&out);//声明在date.h中
void Date::operator<<(ostream& out)//定义在date.cpp中
{
  out<<this->_year <<"年" << this->_month<<"月" << this->_day<<"日";
}
int main()//.cpp中
{
  Date d1(2024, 3, 30);
  d1.operator<<(cout);
 
}

如果我们修改成这样呢.cpp

int main()
{
  Date d1(2024, 3, 30);
   //d1.operator<<(cout);
  cout << d1;
 
}

由于我们的运算符重载是定义在日期类里面的,所以默认*this是左操作数,所以类定义的对象必须放在左边。修改如下:

int main()
{
  Date d1(2024, 3, 30);
   //d1.operator<<(cout);
  d1<<cout;
}

如果我们就要使类对象在右边呢?

所以我们必须将该函数放在全局,但是放在全局的话,类对象的变量都是私有,就不能访问到,我们先改成共有:

void operator<<(ostream& out, Date& d);//声明放全局在date.h中
void operator<<(ostream& out, Date& d)//定义在date.cpp中
{
  out << d._year << "年" << d._month << "月" << d._day << "日";
}
int main()//在.cpp中
{
  Date d1(2024, 3, 30);
   //d1.operator<<(cout);
  cout<<d1;
 
}

如果我们不将变量改成共有,我们全局函数怎么才能访问到类成员变量呢?

friend void operator<<(ostream& out, Date& d);

在声明中加上这个,使全局的函数成为类的友元函数,就可以访问类的变量了。


我们知道变量可以连续赋值,这里可以支持连续输出吗?

赋值运算符从右向左,先把q的值赋值为10,然后再把q的值赋给p,然后把p的值赋给i,实现连续赋值,因此需要返回值

ostream& operator<<(ostream& out, Date& d)//定义
{
  out << d._year << "年" << d._month << "月" << d._day << "日";
  return out;
}
ostream& operator<<(ostream& out, Date& d);//声明
int main()
{
  Date d1 = (2002, 3, 11);
  Date d2 = (2012, 3, 11);
  cout << d1 << d2;
}

既然能输出自定义类型,那怎么使用运算符重载函数实现自定义类型输入呢?

实现如下:

istream& operator>>(istream& in, Date& d);//声明在date.h全局
istream& operator>>(istream& in, Date& d)//date.cpp定义
{
  in>>d._year >> d._month >> d._day ;
  return in;
}
int main()
{
  Date d1 ;
  Date d2 ;
  cin >> d1 >> d2;//给输入
  cout << d1 << d2;//输出
  
}

日期类的安全性修改

比如,如果输入不合法,就提示,我们需要写一个检测的函数

修改后的日期类

date.h

#pragma once
#include<iostream>
using namespace std;
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);
  // >=运算符重载
  bool operator >= (const Date& d);
  // <运算符重载
  bool operator < (const Date& d);
  // <=运算符重载
  bool operator <= (const Date& d);
  // !=运算符重载
  bool operator != (const Date& d);
  bool  isvalid(Date& d);
  // 日期-日期 返回天数
  int operator-(const Date& d);
  void print();
  /*void operator<<(ostream&out);*/
  friend ostream & operator<<(ostream& out, Date& d);
  friend istream& operator>>(istream& in, Date& d);
private:
  int _year;
  int _month;
  int _day;
};
ostream& operator<<(ostream& out, Date& d);
istream& operator>>(istream& in, Date& d);

date.cpp

#include "date.h"
Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
  if (!(this->isvalid(*this)))
  {
    cout << "初始化非法" << endl;
  }
}
void Date:: print()
{
  cout << _year << "." << _month << "." << _day<<endl;
}
Date::Date(const Date& d)
{
  
  _year = d._year;
  _month = d._month;
  _day = d._day;
}
Date::~Date()
{
  
  _year = 0;
  _month = 0;
  _day = 0;
}
int Date:: GetMonthDay(int year, int month)
{
  int arr[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;
  }
  return arr[month];
}
Date& Date:: operator=(const Date& d)
{
  if (this != &d)
  {
    _year = d._year;
    _month = d._month;
    _day = d._day;
  }
  return *this;
}
Date & Date::operator+=(int day)
{
  _day+= day;
  while (_day > GetMonthDay(_year,_month))
  {
    _day -= GetMonthDay(_year, _month);
    _month++;
    if (_month == 13)
    {
      _month = 0;
    }
  }
  return *this;
}
Date Date:: operator+(int day)
{
  Date tmp = *this;
  tmp._day += day;
  while (tmp._day > GetMonthDay(tmp._year, tmp._month))
  {
    tmp._day -= GetMonthDay(tmp._year, tmp._month);
    tmp._month++;
    if (tmp._month == 13)
    {
      tmp._month = 0;
    }
  }
  return tmp;
  
}
Date& Date:: operator-=(int day)
{
  _day -= day;
  while (_day <= 0)
  {
    _month--;
    if (_month == 0)
    {
      _year--;
      _month = 12;
    }
        _day += GetMonthDay(_year, _month);
  }
  return *this;
}
Date Date::operator-(int day)
{
  Date tmp = *this;
  tmp -= (day);
  return tmp;
}
bool Date:: operator>(const Date& d)
{
  if (_year > d._year)
  {
    return true;
  }
  else
  {
    if (_year == d._year)
    {
      if (_month > d._month)
      {
        return true;
      }
      else
      {
        if (_month == d._month)
        {
          if (_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) || *this == (d);
}
bool Date:: operator < (const Date& d)
{
  return !(*this >= (d));
}
bool Date::operator <= (const Date& d)
{
  return  !(*this>(d));
}
bool Date:: operator != (const Date& d)
{
  return  !(*this==(d));
}
Date& Date::operator++()
{
  *this = *this + 1;
  return *this;
}
Date Date:: operator++(int)
{
  Date tmp = *this;
  *this=*this+ 1;
  return tmp;
}
Date Date::operator--(int)
{
  Date tmp =*this;
  *this=*this-1;
  return tmp;
}
Date& Date:: operator--()
{
  *this = *this - 1;
  return *this;
}
int Date::operator-(const Date& d)
{
  Date max = *this;
  Date min = d;
  int flag = 1;
  if (min > (max))
  {
    max = d;
    min = *this;
    flag = -1;
  }
  int n = 0;
  while (max != min)
  {
    n++;
    min++;
  }
  return flag*n;
}
bool Date::isvalid(Date& d)
{
  if (_year < 0 || _month <= 0 || _month>12 || _day<1 || _day>GetMonthDay(_year, _month))
  {
    return false;
  }
  true;
}
ostream& operator<<(ostream& out, Date& d)
{
  out << d._year << "年" << d._month << "月" << d._day << "日";
  return out;
}
istream& operator>>(istream& in, Date& d)
{
  while (1)
  {
    cout << "请输入时间" << endl;
    in >> d._year >> d._month >> d._day;
    if (!d.isvalid(d))
    {
      cout << "输入不合法" << endl;
    }
    else
    {
      break;
    }
    
  }
  return in;
}

权限问题

首先看一个问题

我们这里调用print函数发现调用不动


应该怎么修改呢?

在printhan函数的声明和定义后面加上const

void Date:: print() const//定义
{
  cout << _year << "." << _month << "." << _day<<endl;
}
void print() const;//声明

此时该函数中*this指向的内容不能被修改。现在调用相当于权限平移,就可以了。


此时我们的print函数时加了const

int main()
{
  Date d1 ;
  Date d2(2003,3,3);
  const Date d3(2002,1,2);
  d3.print();
  d2.print();
  
  
}

d2是非const的类对象,也能调用const函数print,因为权限缩小了,所以可以。

总结

成员函数,如果是一个对成员变量只进行读访问的函数,建议函数+const,这样const对象和非const对象都可以使用

如果一个对成员变量要进行读写访问的函数,不能加const,否则不能修改成员变量

  1. const对象可以调用非const成员函数吗? 权限放大
  2. 非const对象可以调用const成员函数吗? 权限缩小
  3. const成员函数内可以调用其它的非const成员函数吗?权限放大
  4. 非const成员函数内可以调用其它的const成员函数吗?权限缩小

权限放大和缩小和平移适用于指针和引用

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

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

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

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

初始化列表

在创建对象时,编译器通过调用构造函数,给对象中各个成员变量一个合适的初始值。

class Date
{
public:
Date(int year, int month, int day)
 {
     _year = year;
     _month = month;
     _day = day;
    _year=1;
 }
private:
int _year;
int _month;
int _day;
};

虽然上述构造函数调用之后,对象中已经有了一个初始值,但是不能将其称为对对象中成员变量的初始化,构造函数体中的语句只能将其称为赋初值,而不能称作初始化。因为初始化只能初始化一次,而构造函数体内可以多次赋值。

初始化列表:以一个冒号开始,接着是一个以逗号分隔的数据成员列表,每个"成员变量"后面跟一个放在括号中的初始值或表达式。

class Date
{
public:
Date(int year, int month, int day)
     : _year(year)
     , _month(month)
     , _day(day)
 {}
private:
int _year;
int _month;
int _day;
};

因为我们的常量,引用必须在定义的时候初始化。

#include<iostream>
using namespace std;
class Date
{
public:
    Date(int year, int month, int day)
    {
        _year = year;
        _month = month;
        _day = day;
        _year = 1;
        n = 1;
    }
private:
    int _year;
    int _month;
    int _day;
    const int n;
};
int main()
{
  Date d1(2003, 3, 11);
}

所以我们常量初始化一定要放在初始化列表中。

#include<iostream>
using namespace std;
class Date
{
public:
  Date(int year, int month, int day)
    :n(1)
    , _year(year)
    , _month(month)
    , _day(day)
  {
  
  
  }
private:
  int _year;
  int _month;
  int _day;
  const int n;
};
int main()
{
  Date d1(2003, 3, 11);
}

引用类型必须在初始化时候给初值

#include<iostream>
using namespace std;
class Date
{
public:
  Date(int year, int month, int day,int&p)
    :n(3)
    , _year(year)
    , _month(month)
    , _day(day)
    ,x(p)
  {
  
  
  }
private:
  int _year;
  int _month;
  int _day;
  const int n=1;
  int& x;
};
int main()
{
  int num = 5;
  Date d1(2003, 3, 11,num);
}

p是num的别名,而x又是p的别名。

3.当我们类成员变量里面有自定义类型的话,并且我们没有在初始化列表初始化,初始化列表会给他调用他自己的默认构造函数完成初始化。(这里的默认构造是我们写的全缺省构造函数)

#include<iostream>
using namespace std;
class A
{
public:
  A(int a=3)
    :_a(a)
  {
    cout << "调用" << endl;
  }
private:
  int _a;
};
class Date
{
public:
  Date(int year, int month, int day,int&p)
    :n(3)
    , _year(year)
    , _month(month)
    , _day(day)
    ,x(p)
    
  {
  
  
  }
private:
  int _year;
  int _month;
  int _day;
  const int n=1;
  int& x;
  A cou;
};
int main()
{
  int num = 5;
  Date d1(2003, 3, 11,num);
}

如果A dou对象没有默认构造呢(默认构造包括全缺省,无参,系统生成的,这里构造有参,所以没有默认构造)

我们可以在初始化列表给自定义类型初始化。

#include<iostream>
using namespace std;
class A
{
public:
  A(int a)
    :_a(a)
  {
    cout << "调用" << endl;
  }
private:
  int _a;
};
class Date
{
public:
  Date(int year, int month, int day,int&p)
    :n(3)
    , _year(year)
    , _month(month)
    , _day(day)
    ,x(p)
    ,cou(5)
    
  {
  
  
  }
private:
  int _year;
  int _month;
  int _day;
  const int n=1;
  int& x;
  A cou;
};
int main()
{
  int num = 5;
  Date d1(2003, 3, 11,num);
}

【注意】

  1. 每个成员变量在初始化列表中只能出现一次(初始化只能初始化一次)
  2. 类中包含以下成员,必须放在初始化列表位置进行初始化:
  • 引用成员变量
  • const成员变量
  • 自定义类型成员(且该类没有默认构造函数时)

同时也可以在初始化列表给指针初始化,可以在初始化列表中检查空间是否申请

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
  A(int a)
    :_a(a)
  {
    cout << "调用" << endl;
  }
private:
  int _a;
};
class Date
{
public:
  Date(int year, int month, int day,int&p)
    :n(3)
    , _year(year)
    , _month(month)
    , _day(day)
    ,x(p)
    ,cou(5)
    ,ptr((int*)malloc(sizeof(int)))
    
  {
    if (ptr == NULL)
    {
      perror("malloc fail");
    }
  
  }
private:
  int _year;
  int _month;
  int _day;
  const int n=1;
  int& x;
  A cou;
  int* ptr;
};
int main()
{
  int num = 5;
  Date d1(2003, 3, 11,num);
}

总结:声明的缺省参数是给初始化列表的,如果初始化列表没有给一个变量初始化,这个变量就拿的是缺省参数的值,自定义类型如果初始化列表没有初始化,就会去调用自己的默认构造函数,来进行初始化,如果没有默认构造函数的话,就要看对象实例化的时候有没有给自己写的构造函数有没有传值,如果没有的话,就是随机值,如果初始化列表给自定义类型初始化了,就没有上面的一系列操作了,初始化列表后还可以在括号里面给变量赋值(除了那3个)相当于构造函数。


单参数构造函数支持隐式类型转换

#include<iostream>
#include<stdlib.h>
using namespace std;
class C
{
public:
  C(int x = 0)
    :_x(x)
  {}
  C(const C& cc)
  {
    cout << "C(const C& cc)" << endl;
  }
private:
  int _x;
};
int main()
{
  C cc2 = 2;
}

编译器优化,连续步骤的·构造,一般会合二为一

和隐式类型转化差不多

如果我们的自定义的对象没有在初始化列表中初始化,并且也没有自己的默认构造函数的话,我们要给缺省值给自定义对象赋值,我们必须在全局实例化一个类对象,然后将该类对象拷贝构造给里面的自定义变量。

#include<iostream>
#include<stdlib.h>
using namespace std;
class C
{
public:
  
  C(int x = 0)
    :_x(x)
  {}
  C(const C& cc)
  {
    cout << "C(const C& cc)" << endl;
  }
private:
  int _x;
};
class Stack
{
public:
  void Push(const C& c)
  {
    
  }
};
int main()
{
  
  Stack st;
  C cc3(3);
  st.Push(cc3);
  st.Push(3);
  return 0;
}

这里如果我们要入一个C类的对cc3,并且cc3类成员变量初始化为3,本来我们需要先给cc3对象赋值,然后再将C类对象cc3入栈,现在支持单参数构造函数支持隐式类型转换,就可以入栈一个类成员变量初始化为3,并且是C类对象。

c++11支持多参数构造函数支持隐式类型转换

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
  
  A(int a1, int a2)
    :_a1(a1)
    ,_a2(a2)
  {}
private:
  int _a1;
  int _a2;
};
int main()
{
  
  A aa1 = { 1, 2 };
  
  return 0;
}

explicit关键字

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
  explicit A(int a1, int a2)
    :_a1(a1)
    ,_a2(a2)
  {}
private:
  int _a1;
  int _a2;
};
int main()
{
  
  A aa1 = { 1, 2 };
  
  return 0;
}

用explicit修饰构造函数,将会禁止构造函数的隐式转换。

成员变量在类中声明次序就是其在初始化列表中的初始化顺序,与其在初始化列表中的先后次序无关

class A
{
public:
    A(int a)
       :_a1(a)
       ,_a2(_a1)
   {}
    
    void Print() {
        cout<<_a1<<" "<<_a2<<endl;
   }
private:
    int _a2;
    int _a1;
};
int main() {
    A aa(1);
    aa.Print();
}

上述代码会出现什么情况?D
A. 输出1 1
B.程序崩溃
C.编译不通过
D.输出1 随机值
因为是按照声明次序初始化,所以_a2初始化的时候,_a1还没有初始化,所以_a2是随机值,然后_a1按照初始化列表初始化为1

static成员

概念

声明为static的类成员称为类的静态成员,用static修饰的成员变量,称之为静态成员变量;用static修饰的成员函数,称之为静态成员函数。静态成员变量一定要在类外进行初始化

class A
{
public:
  A()
  {
    
  }
  A(const A& aa)
  {
    
  }
  
private:
  
  
  int a = 0;
};
A Func()
{
  A aa;
  return aa;
}
int main()
{
  A aa1;
  A aa2;
  
  Func();
  return 0;
}

实现一个类,计算程序中创建出了多少个类对象

1.我们定义一个全局变量统计构造函数和拷贝构造函数调用了多少次

#include<iostream>
#include<stdlib.h>
using namespace std;
int n = 0;
class A
{
public:
  A()
  {
    n++;
  }
  A(const A& aa)
  {
    n++;
  }
private:
  int a = 0;
};
A Func()
{
  A aa;
  return aa;
}
int main()
{
  A aa1;
  A aa2;
  Func();
  cout << n << endl;
  return 0;
}

2.由于全局变量可以在任意位置被修改,我们将n定义在类中,但是类中的n是私有的,我们可以使用静态变量static,然后去掉私有,但是static 必须在类外面定义初始化,这时候n就可以在每个类对象中使用了(突破类域使用n)

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
  A()
  {
    n++;
  }
  A(const A& aa)
  {
    n++;
  }
  int a = 0;
  static int n;
};
int A::n = 0;
A Func()
{
  A aa;
  return aa;
}
int main()
{
  A aa1;
  A aa2;
  Func();
  cout << aa1.n << endl;
  cout << aa2.n << endl;
  cout << A::n << endl;
  return 0;
}

3.使用静态函数返回静态变量,静态函数中没有this指针,只能操作静态变量。

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
  A()
  {
    n++;
  }
  A(const A& aa)
  {
    n++;
  }
  static int GetN()
  {
    
    return n;
  }
private:
  int a = 0;
  static int n;
};
int A::n = 0;
A Func()
{
  A aa;
  return aa;
}
int main()
{
  A aa1;
  A aa2;
  
  Func();
  cout << aa1.GetN() << endl;
  cout << A::GetN() << endl;
  
  return 0;
}

特性

  1. 静态成员为所有类对象所共享,不属于某个具体的对象,存放在静态区
  2. 静态成员变量必须在类外定义,定义时不添加static关键字,类中只是声明
  3. 类静态成员即可用 类名::静态成员 或者 对象.静态成员 来访问
  4. 静态成员函数没有隐藏的this指针,不能访问任何非静态成员
  5. 静态成员也是类的成员,受public、protected、private 访问限定符的限制
目录
相关文章
|
22小时前
|
设计模式 安全 算法
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
17 0
|
22小时前
|
C++ Linux
|
22小时前
|
编译器 C++
【C++】继续学习 string类 吧
首先不得不说的是由于历史原因,string的接口多达130多个,简直冗杂… 所以学习过程中,我们只需要选取常用的,好用的来进行使用即可(有种垃圾堆里翻美食的感觉)
7 1
|
22小时前
|
算法 安全 程序员
【C++】STL学习之旅——初识STL,认识string类
现在我正式开始学习STL,这让我期待好久了,一想到不用手撕链表,手搓堆栈,心里非常爽
16 0
|
22小时前
|
存储 安全 测试技术
【C++】string学习 — 手搓string类项目
C++ 的 string 类是 C++ 标准库中提供的一个用于处理字符串的类。它在 C++ 的历史中扮演了重要的角色,为字符串处理提供了更加方便、高效的方法。
16 0
【C++】string学习 — 手搓string类项目
|
22小时前
|
Java C++ Python
【C++从练气到飞升】06---重识类和对象(二)
【C++从练气到飞升】06---重识类和对象(二)
|
22小时前
|
编译器 C++
【C++从练气到飞升】06---重识类和对象(一)
【C++从练气到飞升】06---重识类和对象(一)
|
22小时前
|
存储 编译器 C语言
【C++从练气到飞升】02---初识类与对象
【C++从练气到飞升】02---初识类与对象
|
22小时前
|
C语言 C++
【C++】string类(常用接口)
【C++】string类(常用接口)
21 1