我目前正在大学学习 Java,在我们介绍新内容的同时我正在努力跟上 C++ 的步伐。在java中,我有独立于创建的对象的静态成员字段和方法。这就是我在 C++ 中的目标。
我在 Collision.h 文件中有一个静态函数。
只有当我在头文件中定义静态函数时,程序才会编译。
//.h file
static void debug() //compiles and function is usable
{
std::cout << "DEBUG from the collision class called in main" << std::endl;
}
//.cpp file
// <nothing>
当我在 .cpp 文件中定义函数时,程序将无法编译。
//.h file
static void debug(); //does not compile
//.cpp file
void debug() //I've tried with and without static keyword here.
{
std::cout << "DEBUG from the collision class called in main" << std::endl;
}
我不知道为什么后一种情况不起作用。 .cpp 文件仅在创建对象时使用吗?
感谢您的帮助。 :)
最佳答案
自由函数已经独立于对象。在 C++ 中,static
有几种不同的含义。对于自由函数,static
意味着该函数具有内部链接,这意味着它仅在当前翻译单元(cpp 文件 + header )中可见。
由于您的函数是在 header 中声明的,因此您不需要 static
关键字,否则包含它的每个文件都需要实现它(它们本质上获得了自己的函数版本)。您也不应该在 header 中定义它 - 将其保留为 void debug();
。而是在 cpp 文件中定义它。
关于c++ - 我的静态函数的 header 和 .cpp 发生了什么?仅在 header 中定义时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617920/