简体   繁体   English

将对象传递给C ++中的函数

[英]Passing objects to functions in C++

I wrote the following code which is working perfectly fine. 我编写了下面的代码,它们工作得很好。 However what confused me was that when I create a Student object for example 'a', and then I call a member function on it a.calculator(a). 但是,令我感到困惑的是,当我创建一个Student对象(例如“ a”),然后在其上调用成员函数a.calculator(a)时。 Isn't it redundant that I'm passing the same object as an argument when I'm using the dot operator to call the function on the same object. 当我使用点运算符在同一个对象上调用函数时,将同一个对象作为参数传递给我,这不是多余的。 Any explanation would be appreciated. 任何解释将不胜感激。

#include <iostream>
using namespace std;

struct Semester{
    int credits;
    int gradePoints;
};

class Student{
private:
    string name;
    string major;
    Semester cgpa[8];

public:
    Student();
    Student(string name, string major);
    int calculator(Student &a);
    void enterGrades(Student &a);
};

Student::Student(){
    name = "-";
    major = "Undeclared";
}
Student::Student(string name_, string major_){
    name = name_;
    major = major_;
}

int Student::calculator(Student& a){
    int cgpa = 0;
    int gpa = 0;
    for (int i = 0; i < 8; ++i){
        gpa = (a.cgpa[i].credits * a.cgpa[i].gradePoints)/ a.cgpa[i].credits;
        cgpa = cgpa + gpa;
    }
    return cgpa/8;
}

void Student::enterGrades(Student& a){
    int credits;
    int gp;

    for (int i = 0; i < 8; ++i){
        cout<<"Enter Semester "<<i+1<<" credits: ";
        cin>>credits;
        a.cgpa[i].credits = credits;
        cout<<"Enter Semester "<<i+1<<" grade points: ";
        cin>>gp;
        a.cgpa[i].gradePoints = gp;
    }
}

int main(){
    Student a("Hasan", "CS");
    a.enterGrades(a);
    cout<<"The students CGPA is "<<a.calculator(a)<<endl;

}

Isn't it redundant that I'm passing the same object as an argument when I'm using the dot operator to call the function on the same object. 当我使用点运算符在同一个对象上调用函数时,将同一个对象作为参数传递给我,这不是多余的。

If you always call with the same object, then that's redundant yes. 如果您始终使用相同的对象进行调用,那是多余的。 However, using a parameter allows you to pass another object than the object of the call. 但是,使用参数可以传递调用对象之外的其他对象。

From another perspective: It is redundant for the function to be a non-static member function since it doesn't use any of the members of this . 从另一个角度看:该函数成为非静态成员函数是多余的,因为它不使用this任何成员。

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

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