6.运算符重载

1.运算符重载

  • 运算符本质:函数
    • 操作数:函数的参数
    • 运算符:函数的名字
    • 运算结果 :返回值
#pragma once
class num
{
	int x;
public:
	num();
	num(const num& other); // 拷贝构造的形参,必须是引用,可以不加const
	~num();
	num operator+(num& b); // 运算符重载

};

——————————————————————————————————————
num num::operator+(num& b) {
	num sum; // 用来存放结果
	sum.x = this->x + b.x;
	return sum;
}


num a=2;
num b =3;
a + b;
a.operator+(c);

类之间的加法,需要实现:operator+ 方法;

进行运算时候调用对应的operator方法;

C++中5个不能重载的运算符:

  • sizeof
  • 点运算符
  • 三目运算符
  • ::域名解析符
  • (.)*成员运算符

友元

  • << 输出运算符(c中的左移运算符)>>输入运算符,不能重载为成员函数的运算符,需要使用友元
  • 对象的私有成员不能在类外访问,如果声明为类的友元函数,那么这个友元函数可以访问类中的成员
  • 友元函数不属于这个类,他可以被外部访问
  • 友元缺点:类的封装被破坏
  • 友元函数也能重载运算符
  • 必须用友元重载的运算符 输入>> 输出<<
  • 必须为成员函数的运算符 = () [] ->
  • 单目运算符 成员 没有参数
  • 双目运算符 成员 只有一个参数
  • 对于运算符重载 ------
    • 必须使用已存在的运算符
    • 作用贴近运算符
    • 不能改变优先级操作
  • 单目运算符 :一般重载成成员。双目运算符:一般重载成友元。
#pragma once
#include<iostream>
using namespace std;
class num
{
	int x;
public:
	num();
	num(const num& other); // 拷贝构造的形参,必须是引用,可以不加const
	~num();
	num operator+(num& b); // 运算符重载
	num& operator++(); // 重写前++运算符
	const num operator++(int); // 重写后++运算符
	friend num operator-(num&a, num&b); //定义友元函数重载‘-’运算符
	friend ostream& operator<<(ostream&os,num&other);//重写<<
	friend istream& operator>>(istream&is,num&other);// 重写>>

};
num::num(){}
num::~num(){}
num::num(const num& other){} //拷贝构造{}
num num::operator+(num& b) {
	num sum; // 用来存放结果
	sum.x = this->x + b.x;
	return sum;
}
num operator-(num&a, num&b) {}
std::ostream& operator<<(std::ostream&os, num&other) {
	os << other.x;
	return os;
}
std::istream& operator>>(istd::am&is, num&other) {
	is >> other.x;
	return is;
}

int main(void) {
	num a; //调用无参构造
	num b = a; // 调用拷贝构造
	num c(a); // 调用拷贝构造
	b(); //重载括号  仿函数
    b(3); //重载括号  仿函数
    
	getchar();
	getchar();
	std::cin.get();
	return 0;
}
  • 特殊:重载’()'括号运算符
void operator()();

友元类 :

  • 一个类可以作为另一个类的友元
  • 使用方法: 一个类中 friend class a
class A{};
class B{
    friend class A;
};
  • 将所有A的成员函数声明为B的友元函数
  • A是B的友元,但是B未必是A的友元
  • ABC三个类,A是B的友元,B是C的友元,A未必是C的友元
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值