简体   繁体   English

C ++朋友功能

[英]C++ friend function

I'm making chess game for my uni and I have to use at least one friend function. 我正在为我的大学制作国际象棋游戏,并且我必须至少使用一个朋友功能。

So here is my BoardField class header: 所以这是我的BoardField类标题:

#include "Game.h"

class BoardField {
private:
    ChessPiece m_piece;
    SDL_Rect m_field;

public:
    BoardField();

    friend void Game::init_board_fields();
};

Partial Game class header: 部分游戏类标题:

class Game {
private:
    //members
    ...

    //methods
    ...
public:
    void init_board_fields();
    ...
};

And the method: 和方法:

void Game::init_board_fields()
{
    int field_width = m_window_props.w / 8;
    int field_height = m_window_props.h / 8;
    int field_index = 0;

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            BoardField field;
            // here I get the error that member m_field is inaccessible
            field.m_field = { j * field_width, i * field_height, field_width, field_width };
            m_board_fields[field_index++] = field;
        }
    }
}

So I get this error (look for comment in last code block). 所以我得到这个错误(在最后一个代码块中查找注释)。 Do I poorly understand friend ? 我对朋友了解不吗? Does this keyword allow access to private members/methods or does something else? 这个关键字是否允许访问私有成员/方法或其他?

I simply want to say that a friend method c++ is not part of any class. 我只是想说一个朋友方法c ++不属于任何类。 This being said, your friend method is not part of the class BoardField but it is trying to access its private member(Which is wrong). 话虽这么说,您的朋友方法不是BoardField类的一部分,但它正在尝试访问其私有成员(这是错误的)。

Game class header has to be implemented in Game.cpp not in BoardField class. 游戏类标头必须在Game.cpp中实现,而不是在BoardField类中实现。 You are getting the error because you are trying to access a private member of BoardField class through a method declared in Game class.Here I am leaving out the friend concept. 因为尝试通过Game类中声明的方法访问BoardField类的私有成员,所以出现了错误。这里我忽略了朋友概念。

A proper way to use friend concept in your case would be to make your BoardField Class a Friend of Game Class. 在您的情况下使用朋友概念的正确方法是使BoardField类成为游戏类的朋友。 This way, Game class will have access to everything in class BoardField. 这样,游戏类将可以访问类BoardField中的所有内容。 This will eventually work in what your are trying to do. 这最终将在您尝试做的事情中起作用。

You simply have to declare : friend BoardField in your Game class. 您只需要在Game类中声明:朋友BoardField即可。

class Game {
private:
    //members
    ...

    //methods
    friend BoardField;
    ...
public:
    void init_board_fields();
    ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM