从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)(下)

简介: 从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)

从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)(中):https://developer.aliyun.com/article/1513647

5.2 赋值运算符重载使用

赋值运算符重载主要有以下四点:

① 参数类型

② 返回值

③ 检查是否给自己复制

④ 返回 *this

#include <iostream>
using namespace std;
 
class Date 
{
public:
  Date(int year = 1, int month = 1, int day = 1) 
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  Date& operator=(const Date& d) 
  {
    if (this != &d)  // 防止自己跟自己赋值(这里的&d是取地址)
    {
      _year = d._year;
      _month = d._month;
      _day = d._day;
    }
    return *this;   // 返回左操作数d1
  }
 
  void Print()
  {
    cout << _year << "年" << _month << "月" << _day << "日" << endl;
  }
 
private:
  int _year;
  int _month;
  int _day;
};
 
int main()
{
  Date d1(2023, 5, 3);
  Date d2(2023, 5, 4);
 
  d1 = d2;
 
  d1.Print();
  d2.Print();
  return 0;
}

       自己给自己赋值是无意义的,这里加 if 语句来判断就是为了防止极端情况下,自己给自己赋值,加上这条判断后就算遇到自己给自己赋值,就会不做处理,直接跳过。

       因为出了作用域 *this 还在,所以我们可以使用引用来减少拷贝。(因为传值返回不会直接返回对象,而是会生成一个拷贝的对象,这里减少了两次拷贝构造的调用)

5.3 默认生成的赋值运算符重载

       赋值运算符重载是默认成员函数,所以如果一个类没有显式定义赋值运算符重载,编译器默认生成复制重载,跟拷贝构造做的事情完全类似:

① 内置类型成员,会完成字节序值拷贝 —— 浅拷贝。

② 对于自定义类型成员变量,会调用它的 operator= 赋值。

把我们自己写的赋值运算符重载注释掉:

#include <iostream>
using namespace std;
 
class Date 
{
public:
  Date(int year = 1, int month = 1, int day = 1) 
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  //Date& operator=(const Date& d) 
  //{
  //  if (this != &d)  // 防止自己跟自己赋值(这里的&d是取地址)
  //  {
  //    _year = d._year;
  //    _month = d._month;
  //    _day = d._day;
  //  }
  //  return *this;   // 返回左操作数d1
  //}
 
  void Print()
  {
    cout << _year << "年" << _month << "月" << _day << "日" << endl;
  }
 
private:
  int _year;
  int _month;
  int _day;
};
 
int main()
{
  Date d1(2023, 5, 3);
  Date d2(2023, 5, 4);
 
  d1 = d2;
 
  d1.Print();
  d2.Print();
  return 0;
}

       既然编译器会自己默认生成,已经可以完成字节序的值拷贝了,我们还需要自己实现吗?当然像日期这样的类是没有必要的,但有时候还是需要自己实现的。比如下面的情况:

#include<iostream>
using namespace std;
typedef int DataType;
class Stack
{
public:
  Stack(int capacity = 10)
  {
    _array = (DataType*)malloc(capacity * sizeof(DataType));
    if (_array == nullptr)
    {
      perror("malloc申请空间失败");
      return;
    }
    _size = 0;
    _capacity = capacity;
  }
 
  void Push(const DataType& data)
  {
    _array[_size] = data;
    _size++;
  }
 
  ~Stack()
  {
    if (_array)
    {
      free(_array);
      _array = nullptr;
      _capacity = 0;
      _size = 0;
    }
  }
private:
  DataType* _array;
  int _size;
  int _capacity;
};
int main()
{
  Stack s1;
  s1.Push(1);
  s1.Push(2);
  s1.Push(3);
  s1.Push(4);
  Stack s2;
  s2 = s1;
  return 0;
}

如果类中未涉及到资源管理,赋值运算符是否实现都可以,一旦涉及到资源管理则必须要实现。


6. const 成员

6.1 const 成员的作用

上面定义的日期类,普通对象对它调用 Print ,是可以调得动的。

#include <iostream>
using namespace std;
 
class Date 
{
public:
  Date(int year = 1, int month = 1, int day = 1) 
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  void Print()
  {
    cout << _year << "年" << _month << "月" << _day << "日" << endl;
  }
 
private:
  int _year;
  int _month;
  int _day;
};
 
int main()
{
  Date d1(2023, 5, 3);
  const Date d2(2023, 5, 4);
 
  d1.Print();
  d2.Print();
  return 0;
}

如果这个对象是 const 的呢?这样编译就报错了:

error C2662: “void Date::Print(void)”: 不能将“this”指针从“const Date”转换为“Date &”

这块报错的原因是什么?这里涉及的问题是 "权限的放大" ,这个知识点在下面这篇博客讲过:

从C语言到C++②(第一章_C++入门_中篇)缺省参数+函数重载+引用_GR C的博客-CSDN博客

此时可以使用 const 修饰类的成员函数来解决这种情况。


6.2 const 修饰类的成员函数

将 const 修饰的类成员函数,我们称之为 const 成员函数。

const 修饰类成员函数,实际修饰的是该成员函数隐含的 this 指针,

表明在该成员函数中不能对类的任何成员进行修改。

这里我们可以在函数后面加 const,保持权限的统一:

#include <iostream>
using namespace std;
 
class Date
{
public:
  Date(int year = 1, int month = 1, int day = 1)
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  void Print() const //这里语法就是加在这里的,虽然有点奇怪
  {
    //void Print(Date* const this)变成了void Print(const Date* const this)
    cout << _year << "年" << _month << "月" << _day << "日" << endl;
  }
 
private:
  int _year;
  int _month;
  int _day;
};
 
int main()
{
  Date d1(2023, 5, 3);
  const Date d2(2023, 5, 4);
 
  d1.Print();
  d2.Print();
  return 0;
}

权限的放大会报错,这里d1是权限的缩小,d2没有改变权限。

       使用建议:建议能加上 const 都加上,这样普通对象和 const 对象都可以调用了。但是,如果要修改成员变量的成员函数是不能加的,比如日期类中 += ++ 等等实现。它是要修改的,加不了就算了。

7. 取地址及const取地址操作符重载(两个默认成员函数)

       这两个运算符一般不需要重载,因为它是默认成员函数,编译器会自己默认生成。一般用编译器自己生成的就够了,所以这里只是简单演示一下使用:

7.1 取地址及const取地址操作符重载(自己实现)

#include <iostream>
using namespace std;
 
class Date 
{
public:
  Date(int year, int month, int day) 
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  Date* operator&() 
  {
    return this;
  }
 
  const Date* operator&() const
  {
    return this;
  }
 
private:
  int _year;
  int _month;
  int _day;
};
 
 
int main()
{
  Date d1(2023, 5, 3);
  cout << &d1 << endl;// 取出d1的地址
 
  const Date d2(2023, 5, 4);
  cout << &d2 << endl;// 取出d2的地址
 
  return 0;
}


7.2 取地址及const取地址操作符重载(默认生成)

直接把我们写的注释掉:

#include <iostream>
using namespace std;
 
class Date 
{
public:
  Date(int year, int month, int day) 
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  //Date* operator&() 
  //{
  //  return this;
  //}
 
  //const Date* operator&() const
  //{
  //  return this;
  //}
 
private:
  int _year;
  int _month;
  int _day;
};
 
 
int main()
{
  Date d1(2023, 5, 3);
  cout << &d1 << endl;// 取出d1的地址
 
  const Date d2(2023, 5, 4);
  cout << &d2 << endl;// 取出d2的地址
 
  return 0;
}

只有特殊情况才需要重载,比如你不想让别人取到你的地址:

可以放到私有,或者自己实现返回空指针:

#include <iostream>
using namespace std;
 
class Date 
{
public:
  Date(int year, int month, int day) 
  {
    _year = year;
    _month = month;
    _day = day;
  }
 
  Date* operator&() 
  {
    return nullptr;
  }
 
  const Date* operator&() const
  {
    return nullptr;
  }
 
private:
  int _year;
  int _month;
  int _day;
};
 
int main()
{
  Date d1(2023, 5, 3);
  cout << &d1 << endl;// 取出d1的地址
 
  const Date d2(2023, 5, 4);
  cout << &d2 << endl;// 取出d2的地址
 
  return 0;
}


本篇完。

目录
相关文章
|
11月前
|
安全 C语言 C++
比较C++的内存分配与管理方式new/delete与C语言中的malloc/realloc/calloc/free。
在实用性方面,C++的内存管理方式提供了面向对象的特性,它是处理构造和析构、需要类型安全和异常处理的首选方案。而C语言的内存管理函数适用于简单的内存分配,例如分配原始内存块或复杂性较低的数据结构,没有构造和析构的要求。当从C迁移到C++,或在C++中使用C代码时,了解两种内存管理方式的差异非常重要。
384 26
|
安全 编译器 C语言
C++入门1——从C语言到C++的过渡
C++入门1——从C语言到C++的过渡
345 2
|
存储 编译器 C++
【c++】类和对象(下)(取地址运算符重载、深究构造函数、类型转换、static修饰成员、友元、内部类、匿名对象)
本文介绍了C++中类和对象的高级特性,包括取地址运算符重载、构造函数的初始化列表、类型转换、static修饰成员、友元、内部类及匿名对象等内容。文章详细解释了每个概念的使用方法和注意事项,帮助读者深入了解C++面向对象编程的核心机制。
443 5
|
C语言 C++
C 语言的关键字 static 和 C++ 的关键字 static 有什么区别
在C语言中,`static`关键字主要用于变量声明,使得该变量的作用域被限制在其被声明的函数内部,且在整个程序运行期间保留其值。而在C++中,除了继承了C的特性外,`static`还可以用于类成员,使该成员被所有类实例共享,同时在类外进行初始化。这使得C++中的`static`具有更广泛的应用场景,不仅限于控制变量的作用域和生存期。
494 10
|
算法 编译器 C语言
【C语言】C++ 和 C 的优缺点是什么?
C 和 C++ 是两种强大的编程语言,各有其优缺点。C 语言以其高效性、底层控制和简洁性广泛应用于系统编程和嵌入式系统。C++ 在 C 语言的基础上引入了面向对象编程、模板编程和丰富的标准库,使其适合开发大型、复杂的软件系统。 在选择使用 C 还是 C++ 时,开发者需要根据项目的需求、语言的特性以及团队的技术栈来做出决策。无论是 C 语言还是 C++,了解其优缺点和适用场景能够帮助开发者在实际开发中做出更明智的选择,从而更好地应对挑战,实现项目目标。
682 0
|
算法 机器人 C语言
ROS仿真支持C++和C语言
ROS仿真支持C++和C语言
742 1
C++(十五) 运算符重载
C++中的运算符重载允许对已有运算符的功能进行重新定义,从而扩展语言功能、简化代码并提升效率。重载遵循特定语法,如 `friend 类名 operator 运算符(参数)`。重载时需注意不可新增或改变运算符数量、语义、优先级、结合性和返回类型。常见示例包括双目运算符 `+=` 和单目运算符 `-` 及 `++`。输入输出流运算符 `&lt;&lt;` 和 `&gt;&gt;` 也可重载。部分运算符只能作为成员函数重载。
|
C语言 C++
实现两个变量值的互换[C语言和C++的区别]
实现两个变量值的互换[C语言和C++的区别]
315 0
|
安全 编译器 C语言
C语言const关键字的用法总结
C语言const关键字的用法总结
177 0
|
安全 编译器 C语言
C语言中的const关键字
C语言中的const关键字
344 2