C+;中的静态函数产生意外结果+;班 我需要一个静态类函数,以便能够在C++中使用GLFW3鼠标回调。当我在函数中使用if语句时,会得到错误的结果。我制作了一些简单的演示代码。通过GLFW3调用更复杂的鼠标回调函数,我得到了类似的结果

C+;中的静态函数产生意外结果+;班 我需要一个静态类函数,以便能够在C++中使用GLFW3鼠标回调。当我在函数中使用if语句时,会得到错误的结果。我制作了一些简单的演示代码。通过GLFW3调用更复杂的鼠标回调函数,我得到了类似的结果,c++,syntax,compilation,static-methods,C++,Syntax,Compilation,Static Methods,我做错了什么 这是我的代码: #include <iostream> class StaticTest { public: StaticTest(); ~StaticTest(); int setCallback(); static void callback(double xpos, double ypos); }; StaticTest::StaticTest() { } StaticTest::~StaticTest() { } void Sta

我做错了什么

这是我的代码:

#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);
}

变量
p
被单位化,并在
p+=xpo中使用其值调用未定义的行为

为什么你认为输出是错误的?你还期待什么?完全无关的旁注:你不写的代码没有bug。如果您的构造函数、析构函数或特殊成员函数不起任何作用,请忽略它们(编译器将生成所需的内容)或将它们设置为默认值(例如:~StaticTest()=default;),而不提供任何定义(编译器为您做了定义)。试图智取编译器的结果往往是痛苦的,而不是有益的。@Jørgen您应该注意编译器的警告
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;