【问题标题】:How can I use a class object in another function? c++如何在另一个函数中使用类对象? C++
【发布时间】:2016-03-26 08:37:39
【问题描述】:

如何在另一个函数中使用 lastLoc 对象的 x 和 y 值,如下面的代码所示。我没有收到任何错误,但是当我在 getPosLoc 函数中打印 lastLoc 的值时,我得到一个长数字(可能是地址):

class solveMaze {
private:
    maze maze;
    mouse m;
    stack<coords> coordStack;
    int x;
    int y;
    int posLocCount = 0;
    coords lastLoc;
};

solveMaze::solveMaze() {
    x = m.x;
    y = m.y;
    coords c(x, y);
    coords lastLoc(c.x, c.y);
    coordStack.push(c);
}

void solveMaze::getPosLoc() {
    if((mazeLayout[x][y-1] == 0) && (x != lastLoc.x) && (y-1 != lastLoc.y)) {
        posLocCount++;
        putUp();
    }

这是 coords.h 删除了不相关的函数以缩短代码:

class coords {
    public:
        coords(){};
        coords(int, int);
        int x;
        int y;
        friend ostream &operator<<(ostream &output, const coords &c);
        bool operator==(coords);
        void operator=(const coords &b);
};


coords::coords(int a, int b) {
    x = a;
    y = b;
}

这是mouse.h:

class mouse {
    private:
        maze maze;
    public:
        mouse();
        int x;
        int y;
};

mouse::mouse() {
    for (int i=0; i<12; i++) {
        for (int j=0; j<29; j++) {
            if (mazeLayout[i][j] == 8){
                x = j;
                y = i;
            }
        }
    }
}

【问题讨论】:

  • x = m.x; m。默认构造的mouse 应该包含什么?

标签: c++ oop object


【解决方案1】:

有几个明显的问题:

  1. coords lastLoc(c.x, c.y);

该语句声明并初始化了一个名为lastLoc的局部变量...它不是引用成员lastLoc。为此,代码需要是

lastLoc = coords(c.x, c.y);
  1. x = m.x;y = m.y;

这些语句使用了没有显式初始化的m,那个类是怎么定义的?

【讨论】:

    【解决方案2】:

    您应该为 x 和 y 创建 getter 和 setter,因为这样会更好地练习。但如果你想参考坐标的 x 或 y。你应该写:

    lastLoc->x
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2013-11-14
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多