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

简介: 【C++】类和对象(下)

拷贝构造函数

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

深拷贝与浅拷贝

对于内置对象,编译器可以直接拷贝,这种拷贝是按字节序进行拷贝的被称作浅拷贝或值拷贝。浅拷贝有个问题就是,如果拷贝对象是指向一个空间的,那么拷贝后的对象也是指向这一空间的,但是显然这是不合理的。这时我们就需要深拷贝了。深拷贝会自己开辟一块和拷贝对象指向空间相似的空间。

e3260a16c88c447f9d8630cbeab57be9.png

特性

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

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

class Date
{
public:
  Date(int year = 2000, int month = 1, int day = 1)
  {
    _year = year;
    _month = month;
    _day = day;
  }
  //Date(const Date d)
  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;
}

29a418a2aead4d0db5decee5cf3d7dab.png


若未显示定义,编译器会生成默认的拷贝构造函数。默认的拷贝构造函数对象是浅拷贝

//这是一段错误的代码,未显示定义拷贝构造函数
class Stack
{
public:
  Stack(size_t capacity = 4)
  {
    _a = (int*)malloc(sizeof(int) * capacity);
    if (NULL == _a)
    {
      perror("malloc申请空间失败");
      exit(-1);
    }
    _capacity = capacity;
    _top = 0;
  }
  ~Stack()
  {
    if (_a)
    {
      free(_a);
      _a = NULL;
      _capacity = 0;
      _top = 0;
    }
  }
  void Push(int data)
  {
    _a[_top] = data;
    _top++;
  }
  void Print()
  {
    for (int i = 0; i < _top; i++)
      cout << _a[i] << " ";
    cout << endl;
  }
private:
  int* _a;
  int _top;
  size_t _capacity;
};
int main()
{
  Stack st1;
  Stack st2(st1);
  st1.Push(1);
  st1.Push(2);
  st1.Push(3);
  st2.Print();
  return 0;
}


de6ca3867a94471894a9a3b7f4be2745.png

 类中如果没有涉及资源申请时,拷贝构造函写不写都可以,但是如果涉及到资源申请时,拷贝构造函数就一定要写。

class Stack
{
public:
  Stack(size_t capacity = 4)
  {
    _a = (int*)malloc(sizeof(int) * capacity);
    if (NULL == _a)
    {
      perror("malloc申请空间失败");
      exit(-1);
    }
    _capacity = capacity;
    _top = 0;
  }
  ~Stack()
  {
    if (_a)
    {
      free(_a);
      _a = NULL;
      _capacity = 0;
      _top = 0;
    }
  }
  Stack(const Stack& st)
  {
    _a = (int*)malloc(sizeof(int) * st._capacity);
    if (nullptr == _a)
    {
      perror("malloc申请空间失败");
      exit(-1);
    }
    memcpy(_a, st._a, sizeof(int) * st._top);
    _top = st._top;
    _capacity = st._capacity;
  }
  void Push(int data)
  {
    _a[_top] = data;
    _top++;
  }
  void Print()
  {
    for (int i = 0; i < _top; i++)
      cout << _a[i] << " ";
    cout << endl;
  }
private:
  int* _a;
  int _top;
  size_t _capacity;
};
int main()
{
  Stack st1;
  st1.Push(1);
  st1.Push(2);
  st1.Print();
  Stack st2(st1);
  st2.Push(3);
  st2.Print();
  Stack st3 = st1;
  st3.Push(4);
  st3.Print();
  return 0;
}

使用场景

  使用已经存在的对象创建新对象;

  函数参数类型是类类型对象;

  函数返回值类型为类类型对象。

赋值运算符重载

运算符重载

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

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

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

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

 用于内置类型的运算符,其含义不能改变;

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

  .*(有个点) :: sizeof ?: . (有个点),这五个运算符不能够重载。

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& d1, const Date& d2)
{
  return d1._year == d2._year
    && d1._month == d2._month
    && d1._day == d2._day;
}
void Test()
{
  Date d1(2023, 3, 5);
  Date d2(2023, 3, 4);
  cout << (d1 == d2) << endl;
}
int main()
{
  Test();
  return 0;
}

赋值运算符重载

  1. 赋值运算符重载格式
    参数类型:const T&,传递引用可以提高传参效率;
    返回值类型:T&,返回引用可以提高返回的效率,有返回值的目的是为了至此连续赋值;
    检测是否自己给自己赋值
    返回*this:要符合连续赋值的含义。
class Date
{
public:
  Date(int year = 2000, 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;
    }
    return *this;
  }
  void Print()
  {
    cout << _year << "/" << _month << "/" << _day << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
int main()
{
  Date d1(2023, 3, 5);
  Date d2, d3;
  d2.Print();
  d3.Print();
  d2 = d3 = d1;
  d2.Print();
  d3.Print();
  return 0;
}

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

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

默认的赋值重载运算符是以值的方式逐字节拷贝。

前置++与后置++的重载

前置++是先++在使用,后置++是先使用在++;

 C++规定,后置++重载时多加一个int类型的参数用作区分,但是这个int类型的参数只是起一个站位的作用,不需要我们管,它会由编译器自动传递一个值。

 实际上前置++和后置++是一个很不好的设定,之后的很多语言规定只有前置或后置++,还有的语言里面直接没有了++。

class Date
{
public:
  Date(int year = 2000, 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++()
  {
    _day += 1;
    return *this;
  }
  //后置++
  Date& operator++(int)
  {
    Date temp(*this);
    _day += 1;
    return temp;
  }
  void Print()
  {
    cout << _year << "/" << _month << "/" << _day << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
int main()
{
  Date d1;
  Date d2(2023, 3, 5);
  d1.Print();
  d1 = d2++;
  d1.Print();
  d1 = ++d2;
  d1.Print();
  return 0;
}

const函数

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

class Date
{
public:
  Date(int year, int month, int day)
  {
    _year = year;
    _month = month;
    _day = day;
  }
  void Print() const
  {
    cout << "Print()" << endl;
    cout << "year:" << _year << endl;
    cout << "month:" << _month << endl;
    cout << "day:" << _day << endl << endl;
  }
private:
  int _year; // 年
  int _month; // 月
  int _day; // 日
};
int main()
{
  Date d1(2022, 1, 13);
  d1.Print();
  const Date d2(2022, 1, 13);
  d2.Print();
  return 0;
}

ba1fe3b998cd42a28b6541c988a6b30a.png


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

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

目录
相关文章
|
3天前
|
设计模式 安全 编译器
【C++11】特殊类设计
【C++11】特殊类设计
22 10
|
8天前
|
C++
C++友元函数和友元类的使用
C++中的友元(friend)是一种机制,允许类或函数访问其他类的私有成员,以实现数据共享或特殊功能。友元分为两类:类友元和函数友元。类友元允许一个类访问另一个类的私有数据,而函数友元是非成员函数,可以直接访问类的私有成员。虽然提供了便利,但友元破坏了封装性,应谨慎使用。
39 9
|
4天前
|
存储 编译器 C语言
【C++基础 】类和对象(上)
【C++基础 】类和对象(上)
|
12天前
|
编译器 C++
【C++】string类的使用④(字符串操作String operations )
这篇博客探讨了C++ STL中`std::string`的几个关键操作,如`c_str()`和`data()`,它们分别返回指向字符串的const char*指针,前者保证以&#39;\0&#39;结尾,后者不保证。`get_allocator()`返回内存分配器,通常不直接使用。`copy()`函数用于将字符串部分复制到字符数组,不添加&#39;\0&#39;。`find()`和`rfind()`用于向前和向后搜索子串或字符。`npos`是string类中的一个常量,表示找不到匹配项时的返回值。博客通过实例展示了这些函数的用法。
|
12天前
|
存储 C++
【C++】string类的使用③(非成员函数重载Non-member function overloads)
这篇文章探讨了C++中`std::string`的`replace`和`swap`函数以及非成员函数重载。`replace`提供了多种方式替换字符串中的部分内容,包括使用字符串、子串、字符、字符数组和填充字符。`swap`函数用于交换两个`string`对象的内容,成员函数版本效率更高。非成员函数重载包括`operator+`实现字符串连接,关系运算符(如`==`, `&lt;`等)用于比较字符串,以及`swap`非成员函数。此外,还介绍了`getline`函数,用于按指定分隔符从输入流中读取字符串。文章强调了非成员函数在特定情况下的作用,并给出了多个示例代码。
|
12天前
|
C++
【C++】string类的使用④(常量成员Member constants)
C++ `std::string` 的 `find_first_of`, `find_last_of`, `find_first_not_of`, `find_last_not_of` 函数分别用于从不同方向查找目标字符或子串。它们都返回匹配位置,未找到则返回 `npos`。`substr` 用于提取子字符串,`compare` 则提供更灵活的字符串比较。`npos` 是一个表示最大值的常量,用于标记未找到匹配的情况。示例代码展示了这些函数的实际应用,如替换元音、分割路径、查找非字母字符等。
|
12天前
|
C++
C++】string类的使用③(修改器Modifiers)
这篇博客探讨了C++ STL中`string`类的修改器和非成员函数重载。文章介绍了`operator+=`用于在字符串末尾追加内容,并展示了不同重载形式。`append`函数提供了更多追加选项,包括子串、字符数组、单个字符等。`push_back`和`pop_back`分别用于在末尾添加和移除一个字符。`assign`用于替换字符串内容,而`insert`允许在任意位置插入字符串或字符。最后,`erase`函数用于删除字符串中的部分内容。每个函数都配以代码示例和说明。
|
12天前
|
安全 编译器 C++
【C++】string类的使用②(元素获取Element access)
```markdown 探索C++ `string`方法:`clear()`保持容量不变使字符串变空;`empty()`检查长度是否为0;C++11的`shrink_to_fit()`尝试减少容量。`operator[]`和`at()`安全访问元素,越界时`at()`抛异常。`back()`和`front()`分别访问首尾元素。了解这些,轻松操作字符串!💡 ```
|
12天前
|
存储 编译器 Linux
【C++】string类的使用②(容量接口Capacity )
这篇博客探讨了C++ STL中string的容量接口和元素访问方法。`size()`和`length()`函数等价,返回字符串的长度;`capacity()`提供已分配的字节数,可能大于长度;`max_size()`给出理论最大长度;`reserve()`预分配空间,不改变内容;`resize()`改变字符串长度,可指定填充字符。这些接口用于优化内存管理和适应字符串操作需求。
|
12天前
|
C++ 容器
【C++】string类的使用①(迭代器接口begin,end,rbegin和rend)
迭代器接口是获取容器元素指针的成员函数。`begin()`返回首元素的正向迭代器,`end()`返回末元素之后的位置。`rbegin()`和`rend()`提供反向迭代器,分别指向尾元素和首元素之前。C++11增加了const版本以供只读访问。示例代码展示了如何使用这些迭代器遍历字符串。