类中静态函数C++意外结果

unexpected results from static function in C++ class

本文关键字:意外 结果 C++ 静态函数      更新时间:2023-10-16

我需要一个静态类函数才能在C++中使用GLFW3鼠标回调。当我在函数中使用 if 语句时,我得到错误的结果。我做了一些简单的演示代码。使用 GLFW3 调用的更复杂的鼠标回调函数,我得到了类似的结果。

我做错了什么?

这是我的代码:

#include <iostream>
class StaticTest
{
public:
StaticTest();
~StaticTest();
int setCallback();
static void callback(double xpos, double ypos);
};
StaticTest::StaticTest()
{
}
StaticTest::~StaticTest()
{
}
void StaticTest::callback(double xpos, double ypos)
{
float p;
static float q;
p += xpos;
p += ypos;
q = p;
std::cout << "p, q before if: " << p << ", " << q << std::endl;
if (p > 2*5)
p = 100;
if (q > 2*5*p/q)
q = 100;
std::cout << "p, q after if: " << p << ", " << q << std::endl;
}
int main()
{
StaticTest st;
StaticTest::callback(1,2);
StaticTest::callback(4,3);
}

这些是终端中具有各种编译器选项的结果:

jb@jbpc $ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
jb@jbpc $ g++ static-test.cpp 
jb@jbpc $ ./a.out 
p, q before if: 3, 3
p, q after if: 3, 3
p, q before if: 10, 10
p, q after if: 10, 10
jb@jbpc $ g++ -O1 static-test.cpp
jb@jbpc $ ./a.out 
p, q before if: 3, 3
p, q after if: 100, 3
p, q before if: 7, 7
p, q after if: 100, 7
float p;
static float q;
p += xpos;

变量p是单位化的,在p += xpos;中使用其值会调用未定义的行为。