c++ - 我的静态函数的 header 和 .cpp 发生了什么?仅在 header 中定义时运行

标签 c++ function static header

我目前正在大学学习 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/

相关文章:

c++ - 无法在 C++ 中重载构造函数

c++ - 如何规避虚拟模板成员函数?

c++ - 多参数模板不能很好地处理友元声明

c++ - 返回一个对象和作用域

java - 主类中使用的每个类都必须是静态的吗?

Java:final 关键字的内存使用情况?

C++ boost 或 STL `y += f(x)` 类型算法

javascript - 如何使图像表现得像文件输入?

python - 如何使 raw_input 调用函数

python - 如何将 .swf 文件嵌入到我的 Google App Engine 应用程序中?