I'm trying to get a friend function of class1
and ships
to access the private members of both, but it says that those members are inaccessible.
The code is below, the problem is in ships.cpp
. I tried to reproduce this problem in an even more simple manner in a single file but it didn't happen there, so I don't know what's wrong here. Maybe it's a circular declaration problem?
ships.h
#ifndef _SHIPS_H_
#define _SHIPS_H_
#include "point.h"
class class1;
class Ships{
public:
friend char* checkpoints();
private:
Point ship[6];
};
#endif // ! _SHIPS_H_
ships.cpp
#include "ships.h"
#include "class1.h"
char* checkpoints(Ships ship, class1 game) {
ship.ship[0];//cannot access private member declared in class 'Ships'
game.smallship;//cannot access private member declared in class 'class1'
return nullptr;
}
class1.h
#ifndef _CLASS1_H_
#define _CLASS1_H_
#include "ships.h"
class class1 {
public:
friend char* checkpoints();
private:
static const int LIVES = 3;
Ships smallship, bigship;
};
#endif
Just making my comment an answer. You declared char* checkpoints()
as a friend function. Declare the correct prototype char* checkpoints(Ships ship, class1 game)
as a friend instead.
You also probably want to use references (maybe const) otherwise the arguments are passed by value (copy): char* checkpoints(Ships& ship, class1& game)