重载
Person(返回类型),operater+(person&p) { person temp;}
利用全局函数
- 若想让自定义函数数据类型进行运算,那么久需要重载+运算符
- 在成员函数或者全局函数里,重写一个+运算符的函数
- 函数名 operator+(){ }
- 运算符重载,也可以提供多个版本
运算符重载也是另一种函数的调用方式
左移运算符重载
注:不要随意乱用符号重载
- 内置数据类型的运算符不可以重载
- Count<<直接对person自定义数据类型进行输出
- 写到全局函数中operator<<(costream & cout,person&p1){}
- 如果重载时想访问p1的私有成员,那么全局函数要做person的友元函数
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& cout, Person& p1);
public:
Person() {}
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
private:
int m_A;
int m_B;
};
ostream& operator<<(ostream& cout, Person& p1) //第一个参数 cout 第二个参数 p1
{
cout << "m_A = " << p1.m_A << " m_B = " << p1.m_B;
return cout;
}
void test01()
{
Person p1(10, 10);
cout << p1 << "helloworld" << endl;
}
int main() {
test01();
system("pause");
return EXIT_SUCCESS;
}
前后递增运算符重载
后置++:先返回值后++
前置++:先++后返回值
- 自己实现int类型Myinteger
- 内部维护以int维护
- Myinteger myint
- Myint ++后置 ++myint 前置
- 重载++运算符 operator()前置 operator++(int)后置
- 前值理念:先++后返回自身;后置理念:先保存原有值,内部++返回临时数据
public:
MyInteger()
{
m_Num = 0;
};
//前置++重载
MyInteger& operator++()
{
this->m_Num++;
return *this;
}
//后置++ 重载
MyInteger operator++(int)
{
MyInteger tmp = *this;
m_Num++;
return tmp;
}
int m_Num;
};
智能指针实现
智能指针用来托管自定义类型的对象,让对象自动释放;开辟到栈上自动释放
- person类有showAge成员函数
- 如果new处理的Person对象,就要让程序员自觉的去释放 delet
- 有了智能指针,让智能指针托管这个person对象,对象的释放就不需要自己操心,可以让智能指针管理
- 为了要让智能指针像普通的Person*指针一样使用,就要重载->和*
赋值运算符重载
判断如果原来已经堆区有内容,先释放
- 系统默认类提供 赋值运算符写法 是简单的拷贝
- 导致如果类中有指向堆区的指针,就可能出现深浅拷贝;所以要重载 = 运算符
- 如果想要链式编程 return*this
class Person2
{
public:
Person2(char * name)
{
this->pName = new char[strlen(name) + 1];
strcpy(this->pName, name);
}
//重载 = 赋值运算符
Person2& operator= ( const Person2 & p)
{
if (this->pName != NULL)
{
delete[] this->pName;
this->pName = NULL;
}
this->pName = new char[strlen(p.pName) + 1];
strcpy(this->pName, p.pName);
return *this;
}
关系运算符重载
- 自定义数据类型 不会内部做比较 == != 所以要重载== !=
函数调用运算符
1、()仿函数 对象()看似像函数调用
2、Myadd() 匿名对象
不要重载&&和||:因为本身有短路特性我们无法实现,所以不要重载
#include<iostream>
#include<string>
using namespace std;
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()
{
Person a("Tony", 18);
Person b("Annie", 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;
}
欢迎关注技术公众号,获取更多软件学习干货!
我们能为你提供什么?
技术辅导:C++、Java、嵌入式软件/硬件
项目辅导:软件/硬件项目、大厂实训项目
就业辅导:就业全流程辅导、技术创业支持
对接企业HR:培养输送优质性人才