c++ getter方法调用构造函数

标签 c++

我是 C++ 和 Opengl 的新手,这里可能遗漏了很多东西,这给了我以下问题:

假设我有一个 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

但是,在 NEXT 更新时,BEFORE 恢复到 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 mouse func 调用包含一切的 gameManager 对象,包括 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;
    }

最佳答案

函数

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

返回 mouseManager 的拷贝。您所做的任何更改都会在拷贝上进行。更改它以返回引用。

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

关于c++ getter方法调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43291528/

相关文章:

c++ - 错误 C2248 : strange error when I use thread

c++ - Qt 计算器问题 - C++

c++ - VTK 未定义引用

c++ - 在 C++ 中实现 Hashmap::模板化数据类型的散列函数

c++ - 为什么我应该更喜欢对智能指针的引用而不是智能指针作为 C++ 中的参数

c++ - CentOS 5 内核头文件

c++ - 蒂姆·斯威尼在想什么? (这个 C++ 解析器是如何工作的?)

c++ - 从 cpp 文件创建头文件 .h

C++ Void双指针干扰另一个

c++ - "clean"在 make 文件中不工作