1.赋值运算符重载
#include<iostream> using namespace std; class Person { friend void test01(); public: Person(int age) { m_Age = new int(age); } /*堆区的数据由程序员手动开辟并手动释放*/ ~Person() { if (m_Age != NULL) { delete m_Age; } } Person& operator=(Person &p) { //编译器提供的浅拷贝 //m_Age = p.m_Age; //应该先判断是否有属性在堆区,如果有先释放干净,再深拷贝 p1=p2 if (m_Age != NULL) { delete m_Age; m_Age = NULL; } //深拷贝 m_Age = new int(*p.m_Age); //返回对象本身 return *this; } private: int* m_Age; }; void test01() { Person p1(18);//手动释放后会导致p2对空间的重复释放,违规操作 Person p2(20); Person p3(30); //p2=p1返回自身才能使得p3也被赋值 p3=p2=p1; cout << "p1年龄为 " << *p1.m_Age << endl; cout << "p2年龄为 " << *p2.m_Age << endl; cout << "p3年龄为 " << *p3.m_Age << endl; } int main() { test01(); }
2.关系运算符(== !=)的重载
#include<iostream> using namespace std; #include<string.h> #include<stdbool.h> class Person { public: Person(string name, int age) { m_Name = name; m_Age = age; } bool operator==(Person p) { if (m_Name == p.m_Name && m_Age == p.m_Age) { return true; } else return false; } bool operator!=(Person p) { if (m_Name == p.m_Name && m_Age == p.m_Age) { return false; } else return true; } private: string m_Name; int m_Age; }; void test01() { Person p1("石暄",38); Person p2("石暄", 38); //if (p1==p2) //{ // cout << "两个对象相同" << endl; //} //else //{ // cout << "不同" << endl; //} if (p1 != p2) { cout << "不等" << endl; } else { cout << "相等" << endl; } } int main() { test01(); }
3.函数调用运算符重载
#include<iostream> using namespace std; #include<string.h> class MyPrint { public: void operator()(string test) { cout << test << endl; } }; void MyPrint02(string test) { cout << test << endl; } void test01() { MyPrint myprint; //类对象为函数调用 //使用起来非常类似于函数调用,因此被称为仿函数 myprint("hello world"); //这个就是函数调用 MyPrint02("hello world"); } class MyAdd { public: int operator()(int num1, int num2) { return num1 + num2; } }; void test02() { MyAdd myadd; int ret = myadd(10, 10); cout << "ret = " << ret << endl; //匿名函数对象MyAdd(特点,当前执行完后立即被释放) cout << MyAdd()(100, 100) << endl; } int main() { /*test01();*/ test02(); }