如何在C ++中输出OOP数组?

时间:2016-11-21 01:16:01

标签: c++

我使用在线c ++编辑器https://www.tutorialspoint.com/compile_cpp_online.php并且不确定为什么它会给我这个错误:

main.cpp: In function 'int main(int, char**)':                                                                                                                
main.cpp:87:127: error: invalid use of non-static member function                                                                       
cout<<setw(20)<<student[i].getLastName()<<setw(20)<<student[i].getFirstName()<<setw(20)<<fixed<<setprecision(2)<<student[i].getGPA<<endl;  

main.cpp:90:16: error: 'system' was not declared in this scope                                                                                       
system("PAUSE"); 

它指向学生[i] .getFirstName(),我不知道为什么。对我来说语法看起来不错,但我不确定我是否遗漏了什么?

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

class Student {
    private:
        string sFirstName;
        string sLastName;
        float sGPA;

    public:
        Student();
        void setFirstName(string name);
        void setLastName(string address);
        void setGPA(float gpa);
        string getFirstName();
        string getLastName();
        float getGPA();
};

Student::Student()
{
    sFirstName="";
    sLastName="";
    sGPA=0.00;
}

void Student::setFirstName(string fName)
{
    sFirstName = fName;
}

void Student::setLastName(string lName)
{
    sLastName = lName;
}

void Student::setGPA(float gpa)
{
    sGPA=gpa;
}

string Student::getFirstName()
{
    return sFirstName;
}

string Student::getLastName()
{
    return sLastName;
}

float Student::getGPA()
{
    return sGPA;
}


//int main(int argc, char** argv) {
int main(int argc, char** argv) {
    //int size =10;
    Student student[3];
    string tempString;
    string tempString2;
    float tempFloat;
    int tempInt;
    for(int i = 0; i <3; i++)
    {
        cout<<"Please enter student's first name: "<<endl;
        cin>>tempString;
        cout<< "Please enter student's last name: "<<endl;
        cin>>tempString2;
        cout<< "Please enter student's first name:" <<endl;
        cin>>tempFloat;

        student[i].setFirstName(tempString);
        student[i].setLastName(tempString2);
        student[i].setGPA(tempFloat);
    }

    //20
    cout<<setw(20)<<"Last Name"<<setw(20)<<"First Name"<<setw(20)<<"GPA"<<endl;
    for(int i = 0; i<3; i++)
    {
        cout<<setw(20)<<student[i].getLastName()<<setw(20)<<student[i].getFirstName()<<setw(20)<<fixed<<setprecision(2)<<student[i].getGPA<<endl;

    }
    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

在本声明中

   cout<<setw(20)<<student[i].getLastName()<<setw(20)<<student[i].getFirstName()<<setw(20)<<fixed<<setprecision(2)<<student[i].getGPA<<endl

使用

student[i].getGPA()

而不是

student[i].getGPA

并添加标题<cstdlib>

#include <cstdlib>

答案 1 :(得分:1)

没有()运算符,函数student [i] .getGPA()不会被调用。 对student [i] .getGPA的调用正在评估getGPA方法的地址。 至于其他错误,请包含由Vlad

指出的cstdlib