简体   繁体   中英

I need help in structure in c++

The program is to take a structure with object name "st" will take age and then first and last name than standard

But it is saying this error

(main.cpp:33:10: error: invalid use of non-static member function 'void Student::age(int)')

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

    struct Student{
    static string f,l;
    static int  a,s;
    void age(int ag);
    void first_name(string fi)
    {
        f=fi;
    }
    void last_name(string la)
    {
        l=la;
    }
    void standard(int st)
    {
        s=st;
    }
};
void Student :: age( int ag)
{
    a=ag;
}

int main() {
     Student st;
     cin >> st.age >> st.first_name >> st.last_name >> st.standard;
     cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;

    return 0;
}

Right now it's really unclear what you're trying to achieve with your code.

First of all, your problem is because trying to to put some input into member functions that take arguments, you need to get your input into temporary arguments and pass them, you should also rename your member function to set_age , set_first_name , etc. to indicate what they're doing.

Student st;

int age;
std::string first_name;
std::string last_name;
int standard;

std::cin >> age >> first_name >> last_name >> standard;

st.set_age(age);
st.set_first_name(first_name);
st.set_last_name(last_name);
st.set_standard(standard);

Then you're trying to output them using the same functions without calling them again, but even if you did, they return void , so nothing. You need a different set of member functions to access those variables.

class Student{
    int age;

    /* rest of the code */

    int get_age() const {
        return age;
    }
};


int main() {
    Student student;
    student.set_age(10);
    std::cout << student.get_age() << '\n';
}

It also looks like you don't know what static means inside a class, right now all your instances of Student class will share age, first_name, last_name and standard, which is probably not what you ment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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