有元关系
1、函数有元
2、成员关系有元
3、类有元
单向(你是我的朋友,我不是你的朋友)
不可继承(爸爸的朋友不是儿子的朋友)
不可传递(A是B的朋友 B是C的朋友 但是A不是C的朋友)
缺点:破坏了封装性 不建议使用友元,不得不使用的时候才使用
#include<iostream>
using namespace std;
//友元关系是单向的
//友元函数
class Test
{
public:
Test(int a, int b) :ma(a), mb(b){}
private:
friend ostream& operator<<(ostream&, const Test&);
//输出函数是Test的朋友,输出可以看到Test的所有东西,
//但Test不是输出函数的朋友,不能访问输出的局部变量
int ma;
int mb;
};
ostream& operator<<(ostream& out, const Test& rhs)
{
out << rhs.ma << " ";
out << rhs.mb << " ";
return out;
}
int main()
{
Test test(10, 20);
cout << test << endl;
return 0;
}
class Node;
class CLink
{
public:
CLink();
private:
Node* phead;
};
class Node
{
private:
int mdata;
Node* pnext;
friend class CLink;//有元类
friend CLink::CLink();//有元成员方法
};
CLink::CLink()
{
phead = new Node();
phead->pnext = NULL;
}
int main()
{
return 0;
}
重载:
1、类型
2、关键字(全局的函数 new delete)
operator new
operator delete
不能重载的:
1、.
2、?:
3、sizeof
4、::