收到错误"invalid use of non-static data member 'stu::n' "

Getting an error "invalid use of non-static data member 'stu::n' "

本文关键字:member stu non-static 错误 invalid use of data      更新时间:2023-10-16
#include <bits/stdc++.h>
using namespace std;
struct stu {
int n;
stu(int _n = 0):n(_n) { }

int add(int a, int b = n-1) {
return a + b;
}
};
int main() {
stu obj = stu(5);
cout << obj.add(10) << endl;
}

编译器显示消息" 无效使用 非静态数据成员 'stu::n' "。 这段代码有什么问题。任何帮助都会很棒。

谢谢。

不能以这种方式使用默认参数。考虑编写两个单独的函数:

struct stu {
int n;
int add(int a, int b) { return a + b; }
int add(int a) { return a + n - 1; }
}
相关文章: