c++ - C++ 中的非静态成员

标签 c++

  1. error C2648: 'stack::Y': 使用成员作为默认参数 需要静态成员
  2. error C2648: 'stack::X' : 使用成员作为默认参数 需要静态成员
  3. IntelliSense:非静态成员引用必须相对于 具体对象
  4. IntelliSense:非静态成员引用必须相对于 具体对象

请帮助修复它

class stack{
    node *head, *tail;
    int maze[10][10], X, Y, _X, _Y;
public:
    stack():head(0), tail(0){};
    ~stack();
    void load();
    void makelist(int = X, int = Y); //error is here
    void push(int, int);
    void pop();
    void print();
};
void stack::load(){
    ifstream fin("maze.txt");
    fin >> X >> Y >> _X >> _Y;
    cout << "Loaded matrix:" << endl << endl;
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            fin >> maze[i][j];
            if (i == X && j == Y)
                cout << "S ";
            else if (i == _X && j == _Y)
                cout << "F ";
            else
                cout << maze[i][j] << " ";
        }
        cout << endl;
    }
}
void stack::makelist(int x, int y)
{
    if (x == _X && y == _Y)
    {
        push(x, y);
        print();
        pop();
        return;
    }
    if (x > 0) if (maze[x - 1][y] == 0) { maze[x][y] = 1; push(x, y); makelist(x - 1, y); pop(); maze[x][y] = 0; }
    if (x < 9) if (maze[x + 1][y] == 0) { maze[x][y] = 1; push(x, y); makelist(x + 1, y); pop(); maze[x][y] = 0; }
    if (y > 0) if (maze[x][y - 1] == 0) { maze[x][y] = 1; push(x, y); makelist(x, y - 1); pop(); maze[x][y] = 0; }
    if (y < 9) if (maze[x][y + 1] == 0) { maze[x][y] = 1; push(x, y); makelist(x, y + 1); pop(); maze[x][y] = 0; }
}

<...>

int main()
{
    stack obj;
    obj.load();
    obj.makelist();
    system("pause");
    return 0;
}

最佳答案

(这是对我旧答案的更正,这是不正确的)

您似乎想使用非静态成员作为参数的默认值,而编译器告诉您这是不可能的。您可以使用重载作为解决方法:

class stack{
    node *head, *tail;
    int maze[10][10], X, Y, _X, _Y;

public:
    void makelist() {makelist(X, Y);} // I added this overload to do what you want
    void makelist(int x, int x);
    ...
};

有些人会说重载比使用默认值更好,因为您可能不希望支持使用 1 个参数调用 makelist,只使用 0 或 2 个参数(或者,如果您确实想要这个,你可以添加另一个重载,带有 1 个参数。

关于c++ - C++ 中的非静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25768514/

相关文章:

c++ - 通用运算符 T() 的 enable_if

c++ - 超小异或神经网络无法学习...我做错了什么?

c++ - 如何对齐堆中的数组?

c++ - 尝试解析保存为std::string的大文本文件

c++ - C++ 中的 RSA 加密

c++ - 使用 SendMessage 将文本输入属于另一个进程的编辑控件

c++ - 为什么 clang 仍然需要 libgcc.a 来编译我的代码?

c++ - 如何将库合并到我的可执行文件中,以便用户不需要拥有 DLL?

c++ - 我对 Include Guards 有一些困惑

c++ - IOS和windows之间如何建立Tcp连接?