类中静态函数C++意外结果
unexpected results from static function in C++ class
我需要一个静态类函数才能在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;
中使用其值会调用未定义的行为。
相关文章:
- 尝试将字符串/字符转换为整数会产生意外结果
- RapidXML - 代码创建意外结果
- 类中静态函数C++意外结果
- 指针数组中的意外结果
- 使用指针访问数组元素时出现意外结果
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++:比较运算符>和字符串文本的意外结果
- 具有意外结果的 C++ 闭包
- yaml-cpp 比较的意外结果
- 每次都出现意外结果
- 在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)
- 如何避免 std::abs 的意外结果?
- 使用嵌套 if 语句的意外结果
- A ^= B ^= A ^= B;C# Visual Studio 中的意外结果
- 逻辑错误,我将获得意外结果
- 在 c++ 中使用异步的意外结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 执行递增和递减时"cout"链接会产生意外结果
- OpenCL - 内核方法返回意外结果
- C++使用 std::get_time 解析 YYMMDD ISO 8601 日期字符串会得到意外结果