当前位置:网站首页>运算符重载
运算符重载
2022-07-29 05:25:00 【阿童沐游】
+,-运算符重载
需要访问私有函数,既可以放在类中,也可以用友元函数,将operator+视为友元。
com com::operator+(com &obj)
{
com t;
t.m_a = obj.m_a + m_a;
t.m_b = obj.m_b + m_b;
return t;
}运算符重载规则
1.不能重载:作用域限定符(::),三目运算符(? :),逗号(,),(.*),(sizeof)
2.重载不能改变优先级与结合性
3.不能改变其操作数
4.不能有默认参数
重载步骤
1.写出函数名称
2.根据操作数写形参
3.根据使用场景写出返回值类型
4.运算符重载不能有默认参数,否则会改变运算符操作数
重载输出,输入运算符
需要在类外重载,因为有ostream与istream
#include <iostream>
using namespace std;
class com
{
friend ostream& operator<<(ostream &out, const com &obj);
private:
int m_a;
int m_b;
public:
com():m_a(1), m_b(2)
{
}
com(int a, int b)
{
m_a = a;
m_b = b;
}
void print()
{
cout << m_a << " + " << m_b << endl;
}
void print1()
{
cout << m_a << " - " << m_b << endl;
}
com operator++();
com operator++(int);
bool operator&&(com& b);
com operator+(com &obj);
com operator-(com &obj);
};
com com::operator-(com &obj)
{
com t;
t.m_a = m_a - obj.m_a;
t.m_b = m_b - obj.m_b;
return t;
}
com com::operator+(com &obj)
{
com t;
t.m_a = obj.m_a + m_a;
t.m_b = obj.m_b + m_b;
return t;
}
bool com::operator&&(com& b)
{
if(m_a == 0 && m_b == 0)
return false;
else
if(b.m_a == 0 && b.m_b)
return false;
else
return true;
}
com com::operator++()
{
this->m_a++;
this->m_b++;
return *this;
}
com com::operator++(int)
{
com t = *this;
m_a++;
m_b++;
return t;
}
ostream& operator<<(ostream &out, const com &obj)
{
out << obj.m_a << " " << obj.m_b;
return out;
}
int main(int argc, char *argv[])
{
com c1(2,0);
com c2(0,1);
com c3(0,0);
// c1++;
// ++c1;
// cout <<++c1<< endl;
if(c3 && (c2.operator+(c1)))
{
cout << "ss" << endl;
}
else
{
cout << "frue" << endl;
}
}
重载逻辑运算符
可以重载,但不能实现短路原理
边栏推荐
猜你喜欢

Unity-默认渲染管线-刻晴卡渲shader

关于【链式前向星】的自学理解

LeetCode #9.回文数

一些工具,插件,软件链接分享给大家~

多线程和并发

Computer network interview questions

From entry to soul: how to use tb6600 single chip microcomputer to control stepping motor with high precision (42/57)

JUC并发知识点

2022暑初二信息竞赛学习成果分享2

Leetcode 83. delete duplicate elements in the sorting linked list
随机推荐
循环链表和双向链表
Leetcode 19. delete the penultimate node of the linked list
UE5 光影基础 阴影全解析 锯齿阴影解决方案 Lumen
Unity-默认渲染管线-刻晴卡渲shader
Leetcode 3. longest substring without repeated characters
动态规划总结
Unity中简单的matcap+fresnel shader的实现
Ml9 self study notes
FPGA based: multi-target motion detection (hand-in-hand teaching ①)
Leetcode 167. sum of two numbers II - input ordered array
#9196 肿瘤面积 题解
动态加载数据
封装——super关键字
关于时间复杂度的个人看法
Leetcode 26. delete duplicates in the ordered array
Official tutorial redshift 04 rendering parameters
Markdown and typora
JUC集合类不安全
Ml8 self study notes
Redshift 2.6.41 for maya2018 水印去除