类函数可以具有不同类对象的参数
Can Class Functions Have Parameters That Are Different Class Objects?
假设我有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对象的指针,以便该方法可以在不制作其副本而不修改其成员的情况下从对象中访问其所需的任何内容。
相关文章:
- 如何在C++中正确引用来自不同类的类的对象?
- C 指针和对象作为不同类的一部分
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 如何生成派生同类对象的类
- 使用转换运算符相互转换两个不同类的对象
- 不同类对象的数组
- (C++) 指向不同类中对象的指针的指针
- 计算不同类的对象数量
- 不同类别的 2 个对象之间的信号/插槽
- 分配不同类中的对象的值
- 未定义的引用:试图初始化来自不同类的对象的指针数组
- 类函数可以具有不同类对象的参数
- 在不同类的对象之间共享变量 (C++)
- 如何将具有不同类(但相同基础)的对象存储在一个变量中
- 如何比较两个不同类的对象
- 分配不同类对象时出现赋值错误
- 读取包含2个不同类的对象的数据文件
- 指向从 1 个基类继承的不同类对象的指针数组
- C++:如何让函数接受来自任何命名空间的具有相同类名的对象
- 尝试创建不同类对象的单个数组