看了这篇博客,将会学到C++的基本操作!(如果不敲代码,可能会一知半解)
12天学好C++ 系列(Day6)
第六天 - 221004
7.C++中的friend和运算符
7.1.friend function函数
C++ 中的友元函数被定义为可以访问类的私有、受保护和公共成员的函数。
朋友函数是使用类主体内的朋友关键字声明的。
我们在类的主体中声明了friend函数,需要访问其私有和保护性数据,从关键字friend开始访问数据。当我们需要同时在两个不同的类之间进行操作时,我们会使用它们。
示例1:全局函数中实现
#include<iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box (): length (0) {}
friend int printLength (Box); //friend function
};
int printLength (Box b)
{
b. length +=10;
return b. length;
}
int main ()
{
Box b;
cout <<" Length of box:"<<printLength (b)<<endl;
return 0;
}
示例2:
#include<iostream>
using namespace std;
class B; //forward declaration.
class A
{
int x;
public:
void setdata (int i)
{
x=i;
}
friend void max (A, B); //friend function.
} ;
class B
{
int y;
public:
void setdata (int i)
{
y=i;
}
friend void max (A, B);
};
void max (A a, B b)
{
if (a.x >= b.y)
std:: cout<< a.x << std::endl;
else
std::cout<< b.y << std::endl;
}
int main ()
{
A a;
B b;
a. setdata (10);
b. setdata (20);
max (a, b);
return 0;
}
结果
7.2.运算符重载operator overloading
对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型.
例如
数字:2=3=5
颜色相加:红色+蓝色=紫色
生活:男人+女人=结婚
当然不光加法,一般的其他运算符也可以进行运算:==,+=,
示例:加号运算符重载
#include <iostream>
using namespace std;
class Person1
{
public:
int m_A;
int m_B;
//1、通过成员函数重载加号运算符
/*
Person1 operator+(Person1 &p)
{
Person1 temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}*/
};
//2、全局函数重载加号
Person1 operator+(Person1 &p1, Person1 &p2)
{
Person1 temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
//3、运算符重载 可以发生函数重载
Person1 operator+(Person1 &p, int val)
{
Person1 temp;
temp.m_A = p.m_A + val;
temp.m_B = p.m_B + val;
return temp;
}
void test01()
{
Person1 p1;
p1.m_A = 10;
p1.m_B = 10;
Person1 p2;
p2.m_A = 20;
p2.m_B = 20;
//成员函数本质的调用
//Person1 p3 = p1.operator+(p2);
//全局函数本质的调用
//Person1 p3 = operator+(p1, p2);
//都可以简化成这样
Person1 p3 = p1 + p2;
Person1 p4 = p1 + 1000;
cout << p3.m_A << endl;
cout << p3.m_B << endl;
cout << p4.m_A << endl;
cout << p4.m_B << endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
总结:
- 即使friend函数的原型出现在类定义中,friend也不是成员函数。
- 我们可以在类定义中的任何地方声明friend函数,即在公共、私有或受保护的部分。
- 我们可以在类定义中的任何地方进行friend声明,即在公共、私有或受保护的部分。
- 违反类的数据隐藏原则,尽量避免。您可以授予友谊但不能接受它,即B 类要成为A 类的朋友,A 类必须明确声明B 类是它的朋友。友谊关系既不是对称的,也不是传递的。朋友关系不能继承。
参考文献:
【1】https://medium.com/@somnathshintre77/friend-function-in-c-a1c2ed2d7e5e
【2】 Friend Function in C++ and classes with Examples - Great Learning
本文含有隐藏内容,请 开通VIP 后查看