友元
一个函数想访问一个类的私有成员时是不允许访问的,但是将这个函数声明成友元之后就可以访问了
#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)、(#)、(. ? ::)这五种运算不能重载
本文为参考滴水三期的学习笔记,若有错误请指正,谢谢