【问题标题】:Getting an error "invalid use of non-static data member 'stu::n' "收到错误“无效使用非静态数据成员 'stu::n'”
【发布时间】:2020-06-27 11:21:44
【问题描述】:
#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;
}

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

谢谢。

【问题讨论】:

  • int b = n-1 是无效的默认参数,如documentation 中所述。

标签: c++ class oop


【解决方案1】:

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

struct stu {
    int n;

    int add(int a, int b) { return a + b; }
    int add(int a) { return a + n - 1; }
}

【讨论】:

    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    相关资源
    最近更新 更多