打印标头中声明的变量时C++崩溃

C++ crashes when printing variable declared in header

本文关键字:变量 C++ 崩溃 声明 打印      更新时间:2023-10-16

我正在用 c++ 制作一个用于 OpenGL 的Camera类。当我尝试打印在 Camera.h 中声明的任何变量时,程序崩溃了。但是如果我设置或获取变量的值,它不会崩溃我做错了什么?

相机.h

    #ifndef CAMERA_H
    #define CAMERA_H
    class Camera
    {
        public:
            Camera();
            Camera(float xP, float yP, float zP);
            void move(float x, float y, float z);
        protected:
        private:
            float xPos, yPos, zPos;
    };
    #endif // CAMERA_H

相机.cpp

    #include "Camera.h"
    #include <iostream>
    #include <GL/glut.h>
    using namespace std;
    Camera::Camera()
    {
    }
    Camera::Camera(float xP, float yP, float zP)
    : xPos(xP), yPos(yP), zPos(zP)
    {
    }
    void Camera::move(float x, float y, float z)
    {
        glTranslatef(-x, -y, -z);
        //None of this crashes:
        xPos = 1;
        yPos = xPos;
        //Crashes here:
        cout << "mainCamera x = " << xPos << endl;
    }

我收到的崩溃消息是:

OpenGL.exe遇到了问题,需要关闭。 对于给您带来的不便,我们深表歉意。


编辑

如果我把线路float xPos, yPos, zPos;放在Camera.h的公共部分,然后打电话

    Camera mainCamera(0.0f, 0.0f, 0.0f);
    cout << "mainCamera x = " << mainCamera.xPos << endl;

。在main.cpp中,它工作得很好并打印:

主摄像头 x = 0

嗯,我想通了。而这个是愚蠢的。我忘了在Main.cpp中包含windows.h,出于某种奇怪的原因,它阻止了浮标被打印出来(???)。它现在运行良好。

#include <windows.h>