C++进阶---友元&运算符重载

友元

一个函数想访问一个类的私有成员时是不允许访问的,但是将这个函数声明成友元之后就可以访问了

#include <stdio.h>
class Person
{
private:
	int x;
	int y;
public:
	Person(int x, int y)
	{
		this->x = x;
		this->y = y;
	}
	//声明友元函数			
	friend void Print(const  Person& refPer);			
};
void Print(const Person& refPer)
{
	printf("%d\n", refPer.x);
	printf("%d\n", refPer.y);
}
int main(int argc, char* argv[])
{
	Person p(1, 2);
	Print(p);
	return 0;
}

什么时候需要使用到友元?

1、运算符重载的某些场合需要用到友元
2、两个类需要共享数据的时候

友元函数和成员函数的区别

1、成员函数有this指针,而友元函数没有this指针
2、友元函数是不能被继承的,就像父亲的朋友未必是儿子的朋友

运算符重载

1、运算符重载就是函数替换,相当于是给一个函数取了一个运算符别名,长相是运算符,本质还是一个函数
2、

#include <stdio.h>
class Number
{
private:
	int lowValue;
	int highValue;
public:
	Number(int lowValue, int highValue);
	void Print();
	Number operator+(const Number& p);
	Number operator-(const Number& p);
	Number operator*(const Number& p);
	Number operator/(const Number& p);
	bool operator>(const Number& p);
	bool operator<(const Number& p);
	bool operator==(const Number& p);
};
Number::Number(int lowValue, int highValue)
{
	this->lowValue = lowValue;
	this->highValue = highValue;
}
void Number::Print()
{
	printf("%d\n", lowValue);
	printf("%d\n", highValue);
}
Number Number::operator+(const Number& p)
{
	this->highValue = this->highValue + p.highValue;
	this->lowValue = this->lowValue + p.lowValue;
	return *this;
}
Number Number::operator-(const Number& p)
{
	this->highValue = this->highValue - p.highValue;
	this->lowValue = this->lowValue - p.lowValue;
	return *this;
}
Number Number::operator*(const Number& p)
{
	this->highValue = this->highValue * p.highValue;
	this->lowValue = this->lowValue * p.lowValue;
	return *this;
}
Number Number::operator/(const Number& p)
{
	this->highValue = this->highValue / p.highValue;
	this->lowValue = this->lowValue / p.lowValue;
	return *this;
}
bool Number::operator>(const Number& p)
{
	if (this->highValue > p.highValue)
	{
		return true;
	}
	return false;
}
bool Number::operator<(const Number& p)
{
	if (this->highValue < p.highValue)
	{
		return true;
	}
	return false;
}
bool Number::operator==(const Number& p)
{
	if (this->highValue == p.highValue)
	{
		return true;
	}
	return false;
}
void Test()
{
	Number p(1, 2), p2(3, 4);
	p = p + p2;
	p.Print();

}
int main(int argc, char* argv[])
{
	Test();
	return 0;
}	

1、++和–可以自己完成,所以不用传参
2、+和-之类的因为先传入了一个this指针,所以可以只传一个参数
3、>和<之类的返回值只存在真和假,所以函数类型需要用bool类型
4、运算符重载就是函数替换
5、(.)、(:😃、(sizeof)、(#)、(. ? ::)这五种运算不能重载

本文为参考滴水三期的学习笔记,若有错误请指正,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值