If I'm understanding you correctly, both
spy
and
info
will have friend methods declared in the other class.
1 2 3 4 5
|
class info
{
// ... stuff ...
friend void spy::stealInfo(info*);
}
|
and
1 2 3 4 5
|
class spy
{
//... stuff
friend void info::spyStuff(spy*);
}
|
The problem is that, with mutually friendly methods, the
info
class needs to see the entire
spy
class to know that it has the
stealInfo()
method. A forward declaration won't do since
info
needs to see the method. So, the
spy
class neds to come before the
info
class. But, for the same reasoning, the
info
class needs to come before
spy
in order to make the
friend void info::spyStuff()
declaration work. This contradiction means that the code you want can't be written.
There are other options. You could make the classes friends
class info { friend class spy; }
and vice versa. Or, you could forget friends and make public functions that take the other class as arguments.
Perhaps something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <string>
#include <iostream>
using namespace std;
class spy;
class info
{
private:
string secretInfo = "133+ p@55vv0|2dz";
public:
void letInfoBeStolen(spy*); // passing spy by non-const reference would be better
void tripAlarm();
};
class spy
{
private:
string stolenInfo;
public:
void stealInfo(string s);
void tripOverAlarm(info*);
};
void info::letInfoBeStolen(spy* s)
{
s->stealInfo(secretInfo);
s->tripOverAlarm(this);
}
void info::tripAlarm()
{
cout << "ALARM!" << endl;
}
void spy::stealInfo(string s)
{
stolenInfo = s;
cout << "I got the data! : " << stolenInfo << endl;
}
void spy::tripOverAlarm(info* i)
{
i->tripAlarm();
cout << "Uh oh ..." << endl;
}
int main()
{
info information;
spy spyMaster;
information.letInfoBeStolen(&spyMaster);
return 0;
}
|
This results in:
I got the data! : 133+ p@55vv0|2dz
ALARM!
Uh oh ...
|
Since
info
only needs to know about the
spy
for an argument, a forward declaration works. It will also be easy to add more methods to either class. The other important thing is that the arguments enforce the fact that only
spy
s can get at the private data.
I admit it breaks the image of a spy secretly stealing private data, but that's a small price to pay for working code.