果然,寫代碼的能力還是靠碼代碼的。看了書,以為會了,結果做題目還是有點懵。
最近繼續看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,存在的目的,讓不是當前類的函數,有權限訪問或修改當前類的私有變量,而定義一個友元,必須先讓當前類知道這是一個類,就要先聲明這個友元。