i've been trying to use the friend function for an assignment, but can't figure out how it works. every class in the assignment has it's own header and cpp files. the assignment is building a maze and I want my "Maze" class to use the data members of my "Player" class. every maze object has 2 players inside it(player array), so i wanted a function that will move a player in the maze and change his coordinates.
side note: haven't fully understood the friend function it seems , because when I was in practice class, we used the friend function on operator overloading for iostream header, which doesn't make sense to me, because how would i have access to the iostream members if i didn't use the "friend" operator inside the iostream header ? doesn't that mean i can bypass and class and change its' private members ?
this is how i tried to use the function moveLeft(), to move a player in the maze: (i've deleted some of the functions in my code here to highlight my problem - the function i want to use is at the bottom for every included code segment)
this is my Player class :
#pragma once
#include <string>
class Player
{
private:
std::string _name;
int _highscore;
int _x, _y;
bool _isAI;
public:
//Constrctors & Destructor
Player();
Player(std::string name, int highscore, int xcoor, int ycoor, bool isAI);
~Player();
friend Player& Maze::moveLeft();
};
this is the Maze Class : Header:
#pragma once
#include "Player.h"
class Maze
{
private :
Room** _rooms = new Room*[MAZE_WIDTH];
Player _player[2];
Direction roll_Direction(Direction d)const;
public:
//Constructors & Destructor
Maze();//Default constructor
Maze(const Maze& c);//Basic Constrcutor
~Maze();//Default Destructor including delete for the allocated memory
Player& moveLeft();
};
CPP:
#include "Maze.h"
Maze::Maze()
{
Maze::~Maze()
{
for (int i = 0; i < MAZE_WIDTH; i++)
{
delete[] this->_rooms[i];
}
delete[] this->_rooms;
}
Player& Maze::moveLeft() {
this->_player[0]._x--;
}
Hope my questions make sense, Thanks, Lidor