天天看點

友元類(上課用)

源程式:

#include <iostream>

using namespace std;

class B;

class A

{

private:

int i;

public:

int set(B&);

int get()

{

return i;

}

A(int x)

{

i = x;

}

};

class B

{

int i;

public:

B(int x)

{

i = x;

}

friend A; //友元類

};

int A::set(B& b)

{

return i = b.i;

}

int main()

{

A a(1);

B b(2);

cout << a.get() << ",";

a.set(b);

cout << a.get() << endl;

return 1;

}

運作結果 :