C++初学者质疑如何访问变量

C++ beginners question how to access variables

基本上我的问题包括何时使用参数以及何时不需要它们。 我尝试从示例中学习,而这个我无法完全理解: 我会将问题添加到行右侧的“//”之后我不明白的部分。 也许有人可以给我一个很好的解释,在什么情况下我需要做什么,或者我可以自己查找的好资源。

class 具有 public 属性的学生:

#include <iostream>


class Student
{
public:
    int stud_ID;
    char stud_Name[22];
    int stud_Age;
    };


我想要包含在 int main() 中的函数:

void studentinformation(Student); //#1Why do I must include (Student) in this fuction?              ->  
                                  // If I dont add this parameter in here, there is no connection ->
                                  //to the function studentinformation(s) in int main.
                                  //Why exactly is that the case ?


获取信息的主要函数:

int main(){
    Student s;

    std::cout<<"Type in ID:";
    std::cin >> s.stud_ID;
    std::cout<<"Type in youre Name:";
    std::cin.ignore();   //
    std::cin.getline(s.stud_Name, 22); //#2 Why is std::getline(std::cin, s.stud_Name) not working ?->
    std::cout<<"Type in age:";         //#3 Or is there a better alternative ?
    std::cin >> s.stud_Age;

    studentinformation(s);             //#4 Why do I must include the parameter s ?
    return 0;

}


打印信息的函数:

void studentinformation(Student s)  // #5 Why do I must include the Parameters ?
{   std::cout<<" Student information:"<< std::endl;
    std::cout<<" Student ID:" << s.stud_ID << std::endl;

    std::cout<<" Name:" <<  s.stud_Name<< std::endl;

    std::cout<<" Age:" << s.stud_Age<< std::endl;
}

  1. studentinformation() 是一个自由函数,与 Student 的任何实例都没有关系,这就是为什么您需要提供一个作为参数。
  2. std::getline() 适用于 std::strings ...
  3. ... 如果您将 char stud_Name[22]; 更改为 std::string stud_Name;.
  4. ,您就是在帮自己一个忙
  5. 原因同 1.
  6. 和1一样的原因。1、4、5问的是同一个问题

另一种方法是使 studentinformation() 成为 Student 成员函数。然后您可以调用 s.studentinformation(); 打印有关该特定学生的信息。

class Student {
public:
    int stud_ID;
    std::string stud_Name; // suggested change
    int stud_Age;

    void studentinformation() const { // const since the object (this) won't be altered
        std::cout << " Student information:" << '\n';
        std::cout << " Student ID:" << stud_ID << '\n';
        std::cout << " Name:" <<  stud_Name << '\n';
        std::cout << " Age:" << stud_Age << '\n';
    }    
};