我正在尝试获取class1ships的朋友函数来访问这两个成员的私有成员,但是它说这些成员不可访问。

代码在下面,问题出在ships.cpp中。我试图以更简单的方式在单个文件中重现此问题,但该问题并未在那里发生,所以我不知道这里出了什么问题。也许这是一个循环申报问题?

船只

#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

最佳答案

只是让我的评论成为答案。您已将char* checkpoints()声明为朋友函数。将正确的原型char* checkpoints(Ships ship, class1 game)声明为朋友。

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

09-09 23:39