朋友功能无法访问私人会员

shi*_*zou 0 c++ private friend c++11

我正在尝试获取朋友的功能class1ships访问两者的私有成员,但它表示这些成员无法访问.

代码如下,问题在于ships.cpp.我试图在一个文件中以更简单的方式重现这个问题,但它没有发生在那里,所以我不知道这里有什么问题.也许这是一个循环声明问题?

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_
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 6

只是让我的评论成为答案.您声明char* checkpoints()为朋友功能.char* checkpoints(Ships ship, class1 game)相反,将正确的原型声明为朋友.

您也可能想要使用引用(可能是const),否则参数将通过值(复制)传递: char* checkpoints(Ships& ship, class1& game)