果然,写代码的能力还是靠码代码的。看了书,以为会了,结果做题目还是有点懵。
最近继续看C++编程思想,看到了友元,就是friend关键字,以前看过也了解。再看一遍,受益匪浅。
先看个代码吧:
#include <iostream>
using namespace std;
class A;
class B {
public:
void functionB(A*);
};
class C {
public:
void functionC(A*);
};
class A {
public:
friend void B::functionB(A*);
friend void C::functionC(A*);
private:
string x;
};
void B::functionB(A *a) {
a->x = "from B";
cout << a->x << endl;
}
void C::functionC(A *a) {
a->x = "from C";
cout << a->x << endl;
}
int main()
{
A a; B b; C c;
b.functionB(&a);
c.functionC(&a);
return 0;
}
友元
这边就可以看出,友元的存在,是为了访问类的私有变量。是私有变量,不是private函数,怎么在类外方位private函数,还在学习中...两个Class,比如class A和class B,B要访问A的私有变量,流程是:声明class A -> 定义class B -> 定义class A,class B中的函数,用class A的指针变量作为形参,来访问A的私有变量。
这是普通的友元,还有嵌套友元,上个代码:
#include <iostream>
#include <cstring>
using namespace std;
const int sz = 20;
struct Holder {
private:
int a[sz];
public:
void initialize();
struct Pointer;
friend Pointer;
struct Pointer {
private:
Holder *h;
int *p;
public:
void initialize(Holder *h);
void next();
void previous();
void top();
void end();
int read();
void set(int i);
};
};
void Holder::initialize() {
memset(a,0,sz * sizeof(int));
}
void Holder::Pointer::initialize(Holder *rv) {
h =rv;
p= rv->a;
}
void Holder::Pointer::next() {
if(p < &(h->a[sz - 1])) p++;
}
void Holder::Pointer::previous() {
if(p > &(h->a[0])) p--;
}
void Holder::Pointer::top() {
p= &(h->a[0]);
}
void Holder::Pointer::end() {
p = &(h->a[sz -1]);
}
void Holder::Pointer::read() {
return *p;
}
void Holder::Pointer::set(int i) {
*p = i;
}
int main()
{
Holder h;
Holder::Pointer hp, hp2;
int i;
h.initialize();
hp.initialize(&h);
h2.initialize(&h);
for(int i = 0; i < sz; i++) {
hp.set(i);
hp.next();
}
hp.top();
hp2.end();
for(i = 0; i < sz; i++) {
cout << "hp = " <<hp.read()
<< ", hp2 = " << hp2.read() << endl;
hp.next();
hp2.previous();
}
}
嵌套友元
在类的public成员里,又定义了一个类,里边的类去访问外边类的private变量,就成了嵌套友元。这个流程和普通友元的相似,在外边的类里,声明友元类 -> 说明是个友元类 -> 定义这个类,里边类的成员函数通过指针访问外边类的私有变量。
友元friend,存在的目的,让不是当前类的函数,有权限访问或修改当前类的私有变量,而定义一个友元,必须先让当前类知道这是一个类,就要先声明这个友元。