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

问题描述 投票:0回答:1

我需要一个静态类函数才能在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
c++ syntax compilation static-methods
1个回答
0
投票
float p;
static float q;

p += xpos;

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

© www.soinside.com 2019 - 2024. All rights reserved.