类函数可以具有不同类对象的参数

Can Class Functions Have Parameters That Are Different Class Objects?

本文关键字:同类 对象 参数 类函数      更新时间:2023-10-16

假设我有2个类,播放器和NPC。在类玩家的标题文件中,我可以拥有一个具有NPC类对象的函数吗?

例如:

player.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文件中具有功能体,则可以将前向声明放在标题中,然后在源文件中包含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.

是的,这是完全可能的,我想添加的一件事是,接收参数作为对象的指针通常是一件好事,因为您不会总是想在内存中副本副本。

除此之外,您可以(并且应该取决于情况)将参数作为指向const对象的指针,以便该方法可以在不制作其副本而不修改其成员的情况下从对象中访问其所需的任何内容。