【问题标题】:c++ change function's variable argumentc ++更改函数的变量参数
【发布时间】:2012-06-10 21:57:41
【问题描述】:

我想更改作为参数传递给此函数的变量:

bool verifyStudent(string id, string name, int grade, int points, string type) {
if(!verifyId(id)){
    cerr << "Please enter 8 charactes id! format: YYMMDDCC\n";
    cin >> id;
    return false;
} else
if(!verifyName(name)){
    cerr << "Please enter name to 35 characters!\n";
    cin >> name;
    return false;
} else
if(!verifyGrade(grade)){
    cerr << "Please enter class between 8 and 12!\n";
    cin >> grade;
    return false;
} else
if(!verifyPoints(points)){
    cerr << "Please enter points between 0 and 300!\n";
    cin >> points;
    return false;
} else
if(!verifyType(type)){
    cerr << "Please enter 1 charater type! format: R,r - regional, D,d - district, N,n - national, I,i - international\n";
    cin >> type;
    return false;
} else {
    return true;
}

}

我应该如何访问给定变量并在其他函数未验证时更改它?

这是我调用函数的方式:

verifyStudent(iId, iName, iGrade, iPoints, iType);

【问题讨论】:

  • 虽然我很乐意回答这类问题,但请认为这是基本的 c++ 知识,可以在前几章/课程的任何书籍或教程中找到和学习。
  • verifyStudent 的每次调用最多允许更正一个值,并且不验证更正,所以我希望你在循环中调用它ala while (!verifyStudent(iId, iName, ...))) ;,然后在现实的系统如果他们意识到他们没有手头的所有信息等,最好有办法让他们取消操作。

标签: c++ function variables arguments


【解决方案1】:

为了更改参数,您必须获取 references

bool verifyStudent(string& id, string& name, int& grade, int& points, string& type) 

虽然我会说这个函数 verifyStudent 不如 verifyAndCorrectStudentIfNeeded 多。

【讨论】:

    【解决方案2】:

    引用:

    因此,C++有两种参数传递机制,按值调用(如 在 Java 中)并通过引用调用。当一个参数被传递 参考,函数可以修改原来的。通过引用调用是 由参数类型后面的 & 表示。

    这是一个利用引用调用的典型函数 [...]

    void swap(int& a, int& b) { [...] }

    More here -> A3.5. Functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-18
      • 2017-10-20
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多