1.运算符重载
2.友元
3.一元运算符重载
4.重载<<运算符
5.类的自动转换和强制类型的转换
1.运算符重载
梗概:
语法格式: 返回类型 operator被重载的运算符(参数列表)
实际调用(本质):int3=int1.opreator+(num2)注意:可以把 “opreator+” 整个看成一个特殊函数
1.简化函数调用方式
2.例子
.h
//自己定义的整型类(将整型封装成类)
//Integar:整型
class Integar
{
private:
int m_value; //实际的整型数字(一般私有对象前面都加m代表member)
public:
Integar();
Integar(int value) :m_value(value) {}; //这个带参的内联函数写大括号的原因是相当于在这里实现,否则就是声明,还是得在cpp文件里面写
//重载加号运算符 operator是关键字;+是需要重载的运算符;括号内是加的对象
Integar operator+(Integar other);
int IntValue() { return m_value; }
//这个intvalue在这里作用是查看的私有成员的函数,学习一下思想
};
.cpp
#include "Integar.h"
//调用默认构造时,给私有m_value设一个值0
Integar::Integar():m_value(0)
{
}
//重载+运算符 当前对象,加新的对象,返回一个对象
Integar Integar::operator+(Integar other)
{
Integar result(this ->m_value+other.m_value); //实际上是两个对象的私有成员在相加 注意c++这么写相当于赋值
//result=this ->m_value+other.m_value
return result;
}
main.cpp
#include <iostream>
#include "Integar.h"
using namespace std;
void Test();
int main()
{
Test(); //主函数内多用函数,也是一种思想
return 0;
}
void Test()
{
Integar int1(100), int2(200), int3(40); //赋初值Integar(int value) :m_value(value) {};
int3 = int1 + int2; //如果不重载,这个加号是不成立的,因为两个Integar类型不能相加
cout << int3.IntValue() << endl;
//这个intvalue在这里作用就是查看int3的私有成员的函数,学习一下思想
}