繁体   English   中英

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

[英]C++ beginners question how to access variables

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

具有公共属性的 Student 类:

#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::string s ...
  3. ...如果你改变了char stud_Name[22];你会帮自己一个忙char stud_Name[22]; std::string stud_Name; .
  4. 出于与 1 中相同的原因。
  5. 出于与 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';
    }    
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM