声明:本文章是在学习了【传智扫地僧】的C++视频后做的笔记。可收藏,可转载。
友元函数
1)友元函数的作用:
类很好的将成员函数以及成员变量进行封装,并且设置public、protected、private用于限制访问。
而友元函数用于破坏类的封装性,可以通过与类“交朋友,获得批准”,对传入全局函数中的对象的私有属性进行修改。用于操作符重载中的<<、>>。
2)实例:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
a1 = 100;
a2 = 200;
}
int getA()
{
return this->a1;
}
friend void setA(A& obj, int a1); //将全局函数拷贝过来,并添加friend关键字即可,位置不限
protected:
private:
int a1;
int a2;
};
void setA(A& obj, int a1) //想访问对象的私有属性,因此需要传入对象引用
{
obj.a1 = a1;
}
void main()
{
A a;
setA(a, 1);
cout << a.getA() << endl; //output:1
cout << "hello,world..." << endl;
system("pause");
}
3)使用步骤:
定义全局函数;
输入参数中有对象的引用;
将函数在此类中进行声明,并添加关键字friend
友元类
1)作用:
友元类用于消息体或者封装的数据,通过一个类可以访问另一个类的私有函数以及私有变量。
2)实例:
#include <iostream>
using namespace std;
class A
{
public:
A(int x)
{
this->x = x;
}
void printA()
{
cout << this->x << endl;
}
friend class B;//注意:声明友元类
protected:
private:
int x;
};
class B
{
public:
B(int y, int x):Aobject(x)//注意:传递初始化参数
{
this->m_y = y;
}
void setData(int x)
{
Aobject.x = x; //注意:调用友元类私有变量
}
void printB()
{
Aobject.printA(); //注意:调用友元类私有函数
}
protected:
private:
A Aobject; //B中包含有友元类对象
int m_y;
};
void main()
{
B b(1, 2);
b.printB();
cout << "hello,world..." << endl;
system("pause");
}