2017-04-08 108 views
1

我很新的C++和OpenGL,也有可能是一些事情,我在这里失踪这是给我以下的问题:C++的getter方法调用构造函数

说,我有一个MouseManager对象它有一个Point(x,y)来存储它的位置。默认构造函数将它设置为Point(50,50)。它有一个方法“moveMouse”,意思是更新这个位置。

void MouseManager::moveMouse(int x, int y) { 
    cout << "values: " << x << " " << y << endl; 
    cout << "BEFORE: " << position.getX() << " " << position.getY() << endl; 
    position = Point(x,y); 
    cout << "AFTER: " << position.getX() << " " << position.getY() << endl; 
} 

通过COUT声明,我已确认以下内容:

values: 614 188 //this is the actual mouse position being passed by glut 
BEFORE: 50 50  //this is the Point values before the update 
AFTER: 614 188 //this is the updated values 

然而,在下次更新中,之前恢复到50,50 - 也就是说,它实际上并没有更新。

values: 614 188 
BEFORE: 50 50 
AFTER: 614 188 
values: 616 187 
BEFORE: 50 50 
AFTER: 616 187 
values: 619 187 
BEFORE: 50 50 
AFTER: 619 187 
values: 623 186 

我一直在试图找出这是为什么,是否我无意中不知何故再次调用构造函数,但我似乎没有要。

目前我的代码设置如下:

  1. 的OpenGL鼠标FUNC调用游戏管理对象包含一切,包括MouseManager。
  2. MouseManager运行moveMouse方法
  3. moveMouse使用Point对象用更新的x和y位置创建一个新的Point(x,y)。

    void callMouseManager(int x, int y){ //from gl 
        game.getMouseManager().moveMouse(x, HEIGHT - y); 
    } 
    ++++++++ 
    MouseManager GameManager::getMouseManager(){ //from inside GameManager class 
        return mouseManager; 
    } 
    

我不知道发生了什么事情,希望有人能帮助我理解我在做什么错。

#include "MouseManager.h" 
    #include <iostream> 

    using namespace std; 

    MouseManager::MouseManager() { 
     cout << "CONSTRUCTOR" << endl; 
     position = Point(50,50); 
    } 

    MouseManager::~MouseManager() { 
     // TODO Auto-generated destructor stub 
    } 

    void MouseManager::moveMouse(int x, int y) { 
     cout << "values: " << x << " " << y << endl; 
     cout << "BEFORE: " << position.getX() << " " << position.getY() << endl; 
     position.setX(x); 
     position.setY(y); 
     cout << "AFTER: " << position.getX() << " " << position.getY() << endl; 
    } 

    Point MouseManager::getPosition() { 
     return position; 
    } 
+0

你还在哪里改变或做任何与'position'有关的事情。因为你必须在其他地方做'position = Point(50,50)'。 – Vallentin

+0

我无法让代码标签在注释中工作,但我只访问了mouseManager的Point对象。我将它存储在行 中的一个新的临时点上。Point mouse = game.getMouseManager()。getPosition(); – Astantos

+0

请将更改添加到问题本身。也特别提到'位置'。 – Vallentin

回答

3

功能

MouseManager GameManager::getMouseManager(){ 
    return mouseManager; 
} 

返回mouseManager副本。您所做的任何更改都是在副本上进行的。将其更改为返回参考。

​​
+0

它的工作原理!非常感谢:D 我知道它必须是我不了解的东西,但我不知道它是什么,因为引用和指针对我来说仍然是非常陌生的。 。 。 – Astantos

+0

@Astantos,不客气。如果你要写的东西不仅仅是作业的简单程序,从长远来看,最好是对这些基本概念有一个深入的了解。 –