Code:
//: C05:Friend.cpp
// Friend allows special access
#include <iostream>
using namespace std;
// Declaration (incomplete type specification):
struct X;
struct Y {
void f(X*);
};
struct X { // Definition
private:
int i;
public:
void initialize();
friend void g(X*, int); // Global friend
friend void Y::f(X*); // Struct member friend
friend struct Z; // Entire struct is a friend
friend void h();
};
void X::initialize() {
i = 0;
}
void g(X* x, int i) {
x->i = i;
}
void Y::f(X* x) {
x->i = 47;
}
struct Z {
private:
int j;
public:
void initialize();
void g(X* x);
void q(X* x);
};
void Z::initialize() {
j = 99;
}
void Z::g(X* x) {
x->i += j;
}
void Z::q(X* x) {
cout << "Z::j == " << j << endl;
cout << "X::i == " << (x -> i) << endl;
}
void h() {
X x;
x.i = 100; // Direct data manipulation
}
int main() {
X x;
Z z;
z.g(&x);
z.q(&x);
getchar();
} ///:~
//: C05:Friend.cpp
// Friend allows special access
#include <iostream>
using namespace std;
// Declaration (incomplete type specification):
struct X;
struct Y {
void f(X*);
};
struct X { // Definition
private:
int i;
public:
void initialize();
friend void g(X*, int); // Global friend
friend void Y::f(X*); // Struct member friend
friend struct Z; // Entire struct is a friend
friend void h();
};
void X::initialize() {
i = 0;
}
void g(X* x, int i) {
x->i = i;
}
void Y::f(X* x) {
x->i = 47;
}
struct Z {
private:
int j;
public:
void initialize();
void g(X* x);
void q(X* x);
};
void Z::initialize() {
j = 99;
}
void Z::g(X* x) {
x->i += j;
}
void Z::q(X* x) {
cout << "Z::j == " << j << endl;
cout << "X::i == " << (x -> i) << endl;
}
void h() {
X x;
x.i = 100; // Direct data manipulation
}
int main() {
X x;
Z z;
z.g(&x);
z.q(&x);
getchar();
} ///:~
out:
Z::j == 4370432
X::i == 8740868
Dobiju se ove adrese (i to ne u hex), umesto integera 99 i 100, zasto?
TX