黑马程序员C++类和对象【5】 —— 运算符重载(蓝桥杯必备知识)万字超详解

简介: 黑马程序员C++类和对象【5】 —— 运算符重载(蓝桥杯必备知识)万字超详解

加号运算符重载

如果现在我们希望对对象的属性进行求和,我们可能会想到用+直接进行相加,那么就让我们先来试试吧,下面是我实例化两个对象的两个属性相加,结果编译器会报错,说我的操作数和运算符不匹配,那么这时候就需要自己手动重载运算符了。


作用:实现两个自定义数据类型相加的运算

使用运算符重载(注意:重载函数名必须是编译器提供的operator+)


成员函数重载

//运算符重载
class Person {
public:
  //1、成员函数重载+号
  Person operator+(Person& p)
  {
    Person temp;
        //this指针指向的是调用该成员函数的对象(p1),这里面的p是指传进来的p2的引用
    temp.m_A = this->m_A + p.m_A;
    temp.m_B = this->m_B + p.m_B;
    return temp;
  }
  int m_A;
  int m_B;
};
void test01()
{
  Person p1;
  p1.m_A = 10;
  p1.m_B = 10;
  Person p2;
  p2.m_A = 10;
  p2.m_B = 10;
  Person p3 = p1 + p2;    //等价于 p1.operator+(p2)
  cout << p3.m_A << " " << p3.m_B << endl;
}
int main() {
  test01();    //调用
  system("pause");
  return 0;
}

全局函数重载

//运算符重载
class Person {
public:
  //1、成员函数重载+号
  //Person operator+(Person& p)
  //{
  //  Person temp;
  //  temp.m_A = this->m_A + p.m_A;
  //  temp.m_B = this->m_B + p.m_B;
  //  return temp;
  //}
  int m_A;
  int m_B;
};
//2、全局函数重载  + 号
Person operator+(Person &p1,Person &p2)
{
  Person temp;
  temp.m_A = p1.m_A + p2.m_B;
  temp.m_B = p1.m_B + p2.m_B;
  return temp;
}
void test01()
{
  Person p1;
  p1.m_A = 10;
  p1.m_B = 10;
  Person p2;
  p2.m_A = 10;
  p2.m_B = 10;
  //Person p3 = p1 + p2;    //成员函数重载本质调用等价于 p1.operator+(p2)
  Person p3 = p1 + p2;      //全局函数重载本质调用等价于 operator+(p1,p2)
  cout << p3.m_A << " " << p3.m_B << endl;
}
int main() {
  test01();
  system("pause");
  return 0;
}

运算符重载也可以发生函数重载

class Person {
public:
  Person() {};
  Person(int a, int b)
  {
    this->m_A = a;
    this->m_B = b;
  }
  //成员函数实现 + 号运算符重载
  Person operator+(const Person& p) {
    Person temp;
    temp.m_A = this->m_A + p.m_A;
    temp.m_B = this->m_B + p.m_B;
    return temp;
  }
public:
  int m_A;
  int m_B;
};
//全局函数实现 + 号运算符重载
//Person operator+(const Person& p1, const Person& p2) {
//  Person temp(0, 0);
//  temp.m_A = p1.m_A + p2.m_A;
//  temp.m_B = p1.m_B + p2.m_B;
//  return temp;
//}
//运算符重载 可以发生函数重载 
Person operator+(const Person& p2, int val)
{
  Person temp;
  temp.m_A = p2.m_A + val;
  temp.m_B = p2.m_B + val;
  return temp;
}
void test() {
  Person p1(10, 10);
  Person p2(20, 20);
  //成员函数方式
  Person p3 = p2 + p1;  //相当于 p2.operaor+(p1)
  cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;
  Person p4 = p3 + 10; //相当于 operator+(p3,10)
  cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
}
int main() {
  test();
  system("pause");
  return 0;
}

总结1:对于内置的数据类型的表达式的的运算符是不可能改变的;


总结2:不要滥用运算符重载

左移运算符重载

比如这个例子,显然下面这个不能输出的。

左移运算符重载的作用:可以输出自定义数据类型

可以转到定义查看cout是ostream类型的

//左移运算符重载
class Person {
  friend ostream& operator<<(ostream& out, Person& p);
public:
  Person(int a, int b)
  {
    this->m_A = a;
    this->m_B = b;
  }
  //成员函数 实现不了(  p << cout 不是我们想要的效果 )
  //void operator<<(Person& p){
  //}
private:
  int m_A;
  int m_B;
};
//全局函数实现左移重载
//ostream对象只能有一个
ostream& operator<<(ostream& out, Person& p) {
    //内部就是一个简单的对象属性的输出
  out << "a:" << p.m_A << " b:" << p.m_B << endl;;
  return out;
}
void test() {
  Person p1(10, 20);
  //如果返回的是void型,后面就不能追加输出了
  cout << p1 << "hello world" << endl; //链式编程
}
int main() {
  test();
  system("pause");
  return 0;
}

总结:重载左移运算符配合友元可以实现输出自定义数据类型


递增运算符重载

作用: 通过重载递增运算符,实现自己的整型数据

class MyInteger {
  friend ostream& operator<<(ostream& out, MyInteger myint);
public:
  MyInteger() {
    m_Num = 0;
  }
  //前置++
  MyInteger& operator++() {
    //先++
    m_Num++;
    //再返回
    return *this;
  }
  //后置++
  MyInteger operator++(int) {
    //先返回
    MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
    m_Num++;
    return temp;
  }
private:
  int m_Num;
};
ostream& operator<<(ostream& out, MyInteger myint) {
  out << myint.m_Num;
  return out;
}
//前置++ 先++ 再返回
void test01() {
  MyInteger myInt;
  cout << ++myInt << endl;
  cout << myInt << endl;
}
//后置++ 先返回 再++
void test02() {
  MyInteger myInt;
  cout << myInt++ << endl;
  cout << myInt << endl;
}
int main() {
  test01();
  //test02();
  system("pause");
  return 0;
}

总结: 前置递增返回引用,后置递增返回值

递减运算符重载

class MyInteger {
  //友元函数,是函数可以调用类里面的私有属性
  friend ostream& operator<<(ostream& out, MyInteger myint);
public:
    MyInteger() {
      //给m_Num赋初值。
      m_Num = 2;
    }
    //前置--
    MyInteger& operator--() {
      //先 -- 
      --m_Num;
      //再返回
      return *this;
    }
    //后置--
    MyInteger operator--(int) {
      //先返回
      MyInteger temp = *this; //记录当前本身的值,然后让本身的减1,但是返回的是以前的值,达到先返回后--;
      m_Num--;
      return temp;
    }
private:
  int m_Num;
};
//全局函数重载左移运算符用于输出
ostream& operator<<(ostream& out, MyInteger myint) {
  out << myint.m_Num;
  return out;
}
//前置-- 先-- 再返回
void test01() {
  MyInteger myInt;
  cout <<--myInt << endl;
  cout << myInt << endl;
}
//后置-- 先返回 再--
void test02() {
  MyInteger myInt;
  cout << myInt-- << endl;
  cout << myInt << endl;
}
int main() {
  test01();
  test02();
  system("pause");
  return 0;  
}

递减和递增一样,前置返回引用,后置返回值。


赋值运算符重载

C++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝
class Person
{
public:
  Person(int age) {
    m_Age = new int(age);
  }
  ~Person() {
    if (m_Age != NULL) {
      delete m_Age;
      m_Age = NULL;
    }
  }
  int *m_Age;
};
void test01()
{
  Person p1(18);
  cout << "p1的年龄为:" << *p1.m_Age << endl;
  Person p2(28);
  p2 = p1;
  cout << "p1的年龄为:" << *p2.m_Age << endl;
}
int main() {
  test01();
  system("pause");
  return 0;
}

写了个析构函数,释放了自己手动在堆上面申请的内存 ,结果出现崩溃了。。。

这里实际上是浅拷贝的问题。


p1和p2公用一块堆内存18,并没有再重新开辟和p1的属性值一样的空间给p2,他们都指向这一块内存。


在函数执行完之后,p2被释放了,再判断p2空间是否为空,不为空释放一次,p1进行同样操作。

堆区内存重复释放,重新崩溃!

解决方案:利用深拷贝,解决浅拷贝带来的问题。

  //重载赋值运算符
  void operator=(Person& p)
  {
    //编译器是提供浅拷贝
    //m_Age = p.m_Age;
    //应该先判断编译器是否有属性在堆区,如果有先释放干净,然后再深拷贝
    if (m_Age != NULL) {
      delete m_Age;
      m_Age = NULL;
    }
    //深拷贝
    m_Age = new int(*p.m_Age);

直接在类里面添加上面代码就可以实现了


但是,你以为这就完了吗


如果这时候要求连续赋值操作,p3 = p2 = p1;则会报错,为啥呢?


仔细看,你前面返回的是void类型,这里需要返回对象本体Person&。


重载部分代码:

  //重载赋值运算符
  Person& operator=(Person& p)
  {
    //编译器是提供浅拷贝
    //m_Age = p.m_Age;
    //应该先判断编译器是否有属性在堆区,如果有先释放干净,然后再深拷贝
    if (m_Age != NULL) {
      delete m_Age;
      m_Age = NULL;
    }
    //深拷贝
    m_Age = new int(*p.m_Age);
    //返回对象本身
    return *this;
  }

总结:

 先在堆区开辟内存

重载流程:

  1.        判断是否有内存,进行清空操作。
  2.        进行深拷贝
  3.        返回自身

关系运算符重载

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

class Person
{
public:
  Person(string name, int age)
  {
    this->m_Name = name;
    this->m_Age = age;
  };
    //==的重载
  bool operator==(Person & p)
  {
    if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
    //!=的重载
  bool operator!=(Person & p)
  {
    if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
    {
      return false;
    }
    else
    {
      return true;
    }
  }
  string m_Name;
  int m_Age;
};
void test01()
{
  //int a = 0;
  //int b = 0;
  Person a("孙悟空", 18);
  Person b("孙悟空", 18);
  if (a == b)
  {
    cout << "a和b相等" << endl;
  }
  else
  {
    cout << "a和b不相等" << endl;
  }
  if (a != b)
  {
    cout << "a和b不相等" << endl;
  }
  else
  {
    cout << "a和b相等" << endl;
  }
}
int main() {
  test01();
  system("pause");
  return 0;
}

函数调用运算符重载(仿函数)

  • 函数调用运算符 () 也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活
class MyPrint
{
public:
  void operator()(string text)
  {
    cout << text << endl;
  }
};
void test01()
{
  //重载的()操作符 因为调用的时候和函数调用很像,所以也称为仿函数
  MyPrint myFunc;
  myFunc("hello world");
}
class MyAdd
{
public:
  int operator()(int v1, int v2)
  {
    return v1 + v2;
  }
};
void test02()
{
  MyAdd add;
  int ret = add(10, 10);
  cout << "ret = " << ret << endl;
  //匿名函数对象调用  
  cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}
int main() {
  test01();
  test02();
  system("pause");
  return 0;
}

记住:仿函数非常灵活,没有固定的写法。

相关文章
|
12月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
463 12
|
10月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
250 0
|
10月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
390 0
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
231 16
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
823 6