C + + 运 算 符 重 载 C++运算符重载 C++运算符重载
运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
38.类和对象-C++运算符重载-加号运算符重载
加号运算符重载
作用:实现两个自定义数据类型相加的运算
#include <iostream> using namespace std; // 左移运算符重载 class Person { public: //利用成员函数重载 左移运算符 p.operator<<(cout)简化版本p <<cout //不会利用成员函数重载 << 运算符,因为无法实现,cout在左侧 // void operator<<(cout) // { // } int my_a; int my_b; }; //只能利用全局函数重载左移运算符 ostream& operator<<(ostream &cout, Person& p) // 本质 operator<< (cout,p)简化cout<<p { cout << "my_a= " << p.my_a << " my_b" << p.my_b; return cout; } void test01() { Person p1; p1.my_a = 100; p1.my_b = 200; cout << p1<<endl ; } int main() { test01(); return 0; }
39.类和对象-C++运算符重载-左移运算符重载
#include <iostream> using namespace std; // 左移运算符重载 class Person { friend ostream& operator<<(ostream& cout, Person& p); public: Person(int a ,int b) { my_a = a; my_b = b; } private: //利用成员函数重载 左移运算符 p.operator<<(cout)简化版本p <<cout //不会利用成员函数重载 << 运算符,因为无法实现,cout在左侧 // void operator<<(cout) // { // } int my_a; int my_b; }; //只能利用全局函数重载左移运算符 ostream& operator<<(ostream &cout, Person& p) // 本质 operator<< (cout,p)简化cout<<p { cout << "my_a= " << p.my_a << " my_b" << p.my_b; return cout; } void test01() { Person p1(255,256); cout << p1<<endl ; } int main() { test01(); return 0; }
40.类和对象-C++运算符重载-递增运算符重载
递增运算符重载
作用:通过重载递增运算符,实现自己的整型数据
#include <iostream> using namespace std; // 重载递增运算符 //自定义整型 class MyInteger { friend ostream& operator<<(ostream& cout, MyInteger myint); private: int my_num; public: MyInteger() { my_num = 0; } // 重载前置++运算符 MyInteger& operator++() { my_num++; return *this; } // 重载后置++运算符 //void operator++(int) int代表占位参数,可以用于区分前置和后置递增 MyInteger operator++(int) { // 先记录当时结果 MyInteger temp = *this; // 后递增 my_num++; // 最后将记录结果做返回 return temp; } }; // 重载<<运算符 ostream& operator<<(ostream& cout,MyInteger myint) { cout << myint.my_num; return cout; } void test01() { MyInteger myint; cout << ++(++myint) << endl; cout << myint << endl; } void test02() { MyInteger myint; cout << myint++ << endl; cout << myint << endl; } int main() { test02(); return 0; }
41.类和对象-C++运算符重载-赋值运算符重载
C++编译器至少给—个类添加4个函数
1.默认构造函数(无参,函数体为空)
⒉.默认析构函数(无参,函数体为空)
3.默认拷贝构造函数,对属性进行值拷贝
4.赋值运算符operator=,对属性进行值拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题
42.类和对象-C++运算符重载-关系运算符重载
43.类和对象-C++运算符重载-函数调用运算符重载