簡體   English   中英

c ++ getter方法調用構造函數

[英]c++ getter method calling constructor

我對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鼠標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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM