- error C2648: 'stack::Y': 使用成员作为默认参数 需要静态成员
- error C2648: 'stack::X' : 使用成员作为默认参数 需要静态成员
- IntelliSense:非静态成员引用必须相对于 具体对象
- 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/