c++ - 类函数可以有不同类对象的参数吗?

标签 c++ function class object parameters

假设我有 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/

相关文章:

c - 如何在函数中使用指针?

arrays - 将元胞数组的内容作为单独的输入参数传递给 MATLAB 中的函数

MySQL 函数返回多于 1 行

class - Bootstrap 3 col-sm-offset-x 影响 col-md-x 结构

javascript - 将键和原型(prototype)方法转换为驼峰式

c++ - 浏览器中的多线程 WebAssembly 比单线程慢,为什么?

c++ - 等价于 C++ 中的 Swift 尾随闭包

php - 如何使用 php 类函数将对象数据存储在 mysql 数据库中?

c++ - 从 C++ 传输错误字符串 => C 包装的 API(多线程)

C++: "error: expected ' ,' or ' .. .' before ' (' token"