有人能帮助我如何从类中调用这个函数参数以显示在我的输出中吗

Can anyone help me how to call this function parameter from class to be displayed in my output

本文关键字:参数 函数 显示 输出 我的 调用 帮助      更新时间:2023-10-16

我使用函数重载的代码是一种代码,用户必须输入4门科目的指针及其学时,这样它才能打印出他们的GPA。问题是我在Student中有3个参数(字符串test123,字符串nama,字符串vinto)。但我只想显示字符串中的任意一个。比方说我想把Vinto打印出来。如何在Display函数中调用vinto,使其打印出vinto。这是我的编码。

CPP.CPP

#include <iostream>
#include "student.h"
using namespace std;
void main(void)
{
    string nama;
    string test123;
    int i;
    Student StudentA(test123, nama, "vinto");
    cout << "key in points for 4 subjectn";
    StudentA.Getpointers();
    StudentA.Display(test123);
}

学生.h

#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
    Student(string test123, string nama, string vinto );
    void Getpointers();
    void Display(string name);
private:
    double points[4];
    int creditHours[4];
    string name;
    double CalculateGPA();
};

学生.cpp

#include <iostream>
#include <iomanip>
#include<string>
#include "student.h"
using namespace std;
Student::Student(string test123, string nama, string vinto)
{
    name = nama;
}
void Student::Getpointers()
{
    for (int i = 0; i<4; i++)
    {
        cout << "points for subject :" << i + 1 << endl;
        cin >> points[i];
        cout << "credit hour for subject " << i + 1 << endl;
        cin >> creditHours[i];
    }
}
void Student::Display(string name)
{
    cout << "Hello " << name << endl;
    cout << "Your current GPA is " << setprecision(3) << CalculateGPA() << endl;
}
double Student::CalculateGPA()
{
    double totalpoints = 0;
    int totalcreditHours = 0;
    for (int i = 0; i<4; i++)
    {
        totalpoints += (points[i] * creditHours[i]);
        totalcreditHours += creditHours[i];
    }
    return totalpoints / totalcreditHours;
}

好吧,构造函数的vinto参数没有保存在任何位置,所以在本例中无法将其取回。但是,您可以存储它:

首先,在类中添加一个vinto字段:

class Student
{
public:
    Student(string test123, string nama, string vinto );
    void Getpointers();
    void Display(string name);
private:
    double points[4];
    int creditHours[4];
    string name;
    string vinto;
    double CalculateGPA();
};

然后,将vinto参数值存储在此字段中:

Student::Student(string test123, string nama, string vinto)
{
    name = nama;
    this->vinto = vinto;
}

在此之后,您可以使用vinto:

void Student::Display(string name)
{
    cout << "Hello " << name << endl;
    cout << "Your current GPA is " << setprecision(3) << CalculateGPA() << endl;
    cout << "Your vinto is " << vinto << endl;
}

此外,有点奇怪的是,您将学生的name存储在对象字段中,但使用另一个名称(传递给Student::Display)向他问好。