假设我有 2 个类,玩家和 npc。在类玩家的头文件中,我可以有一个以 npc 类对象作为参数的函数吗?
例如:
播放器.h:
void somefunc(npc npc1);
最佳答案
是的,只要遇到该类型的定义或前向声明,这是允许的。您还可以拥有指向其他类型的指针或引用,甚至是同一类类型的参数。
class A {};
class B {
public:
void funcA(A a) {}
void funcAPtr(A* p) {}
void funcARef(A& r) {}
void funcB(B b) {}
};
// ...
A a;
B b;
b.funcA(a);
这实际上是面向对象编程的关键原则之一。
在您的具体情况下,您希望首先为 npc
定义一个定义,因此它可能看起来像这样:
// npc.h
class npc {};
// -----
// player.h
#include "npc.h"
class player {
public:
void somefunc(npc npc1);
};
或者,如果您在.cpp
文件中有函数体,您可以只在 header 中放置前向声明,并在源文件中包含npc.h
.这通常更安全,尤其是在您可能遇到循环依赖问题的情况下。
// npc.h
class npc {};
// -----
// player.h
class npc;
class player {
public:
void somefunc(npc npc1);
};
// -----
// player.cpp
#include "player.h"
#include "npc.h"
void player::somefunc(npc npc1) {}
// Note that "npc"'s header must be included before the type is actually used.
// For example, it needs to be included before the function's body, even though a
// forward declaration is enough for the function's prototype to work properly.
关于c++ - 类函数可以有不同类对象的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38024944/