Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在两个类之间使用友元函数_C++_Friend Function - Fatal编程技术网

C++ 在两个类之间使用友元函数

C++ 在两个类之间使用友元函数,c++,friend-function,C++,Friend Function,我一直试图在作业中使用friend函数,但不知道它是如何工作的。 作业中的每个类都有自己的头文件和cpp文件。 作业是构建一个迷宫,我希望我的“迷宫”类使用我的“玩家”类的数据成员。 每个迷宫对象里面都有2个玩家(玩家数组),所以我想要一个函数来移动迷宫中的玩家并改变他的坐标 旁注: 我似乎还没有完全理解friend函数,因为当我在练习课上时,我们在iostream头的操作符重载上使用了friend函数,这对我来说没有意义,因为如果我没有在iostream头中使用“friend”操作符,我如何访

我一直试图在作业中使用friend函数,但不知道它是如何工作的。 作业中的每个类都有自己的头文件和cpp文件。 作业是构建一个迷宫,我希望我的“迷宫”类使用我的“玩家”类的数据成员。 每个迷宫对象里面都有2个玩家(玩家数组),所以我想要一个函数来移动迷宫中的玩家并改变他的坐标

旁注: 我似乎还没有完全理解friend函数,因为当我在练习课上时,我们在iostream头的操作符重载上使用了friend函数,这对我来说没有意义,因为如果我没有在iostream头中使用“friend”操作符,我如何访问iostream成员?这难道不意味着我可以绕过和类并更改其“私有成员”吗

这就是我如何尝试使用函数moveLeft(),在迷宫中移动玩家的方法: (我在这里删除了代码中的一些函数,以突出我的问题-我要使用的函数位于包含的每个代码段的底部)

这是我的玩家课程:

#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();
};
CPP:

#包括“Maze.h”
梅兹::梅兹()
{
梅兹::~Maze()
{
对于(int i=0;i\u房间[i];
}
删除[]此->\u房间;
}
Player&Maze::moveLeft(){
这个->_玩家[0]。_x--;
}
希望我的问题有意义, 谢谢
Lidor

旁注是一个完全独立的问题,但除非您修改了
标题本身,否则您没有访问
std::ostream
std::istream
的任何私有成员。通过类
MyClass
中的好友声明,操作符重载将获得对
MyClass
和nothi的私有成员的访问权ng else。关于实际问题:这里是否有使用
friend
函数的外部要求?将
Player::moveLeft()
作为公共函数而不是使用Friends(这是C++中最强的耦合类型)似乎更合理它也将引入这两个类之间的循环依赖。欢迎使用堆栈溢出。我建议您阅读C++ Guru Scott Meyers的经典文章。。它应该回答关于何时应该使用friend函数的问题。在这里,我认为您不应该使用它。最好创建小的、松散耦合的类。在这里尝试使它们成为朋友时,将它们紧密耦合,因为您将一个类绑定到实现(而不仅仅是接口)另一个。OOP的构建块之一是封装。类的设计应确保其他类只能通过公共成员访问它们。在您的情况下,我看不出有任何理由不可能做到这一点。friend属性是由实现类授予的,而不是由用户授予的。
#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();
};
#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--;
}