好友功能无法访问私有成员
Friend function can't access private members
我正在尝试获取 class1
和 ships
的友元函数来访问两者的私有成员,但它说这些成员不可访问。
代码如下,问题在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_
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)
我正在尝试获取 class1
和 ships
的友元函数来访问两者的私有成员,但它说这些成员不可访问。
代码如下,问题在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_
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)