|
||
|
Why friend functions are needed
Privileged access to more than one class
A function multiplying a vector by a matrix, as represented by these two classes, could be written efficiently if it had access to the
private members of both classes. It would be a friend function of both classes.
class matrix; //forward reference
class vect {
public:
friend vect mpy(const vect& v, const matrix& m);
.....
private:
int* p;
int size;
};
class matrix {
public:
friend vect mpy(const vect& v, const matrix& m);
.....
private:
int** p;
int s1, s2;
};
vect mpy(const vect& v, const matrix& m)
{
assert(v.size == m.s1); //check sizes
//use privileged access to p in both classes
vect ans(m.s2);
int i, j;
for (i = 0; i <= m.s2; ++i) {
ans.p[i] = 0;
for (j = 0; j <= m.s1(); ++j)
ans.p[i] += v.p[j] * m.p[j][i];
}
return ans;
}
A minor point is that a forward declaration of the class matrix is necessary. This is because the function mpy()
must appear in both classes, and it uses each class as an argument type.
|
||
|
|
||