如何在另一个函数中使用类对象?c++

How can I use a class object in another function? c++

本文关键字:对象 c++ 另一个 函数      更新时间:2023-10-16

如何在另一个函数中使用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;
}

这是鼠标。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;
            }
        }
    }
}

有几个明显的问题:

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

此语句声明并初始化一个名为lastLoc的局部变量。。。它是指成员CCD_ 3的而不是。为此,代码需要是

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

这些语句使用尚未明确初始化的m,该类是如何定义的?

您应该为x和y制作getter和setter,因为这是更好的练习。但如果你想参考coord的x或y,你应该写:

lastLoc->x