简体   繁体   English

我需要 c++ 结构方面的帮助

[英]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该程序是采用 object 名称“st”的结构将采用年龄,然后是名字和姓氏比标准

But it is saying this error但它说这个错误

(main.cpp:33:10: error: invalid use of non-static member function 'void Student::age(int)') (main.cpp:33:10:错误:无效使用非静态成员 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.首先,您的问题是因为尝试将一些输入放入采用 arguments 的成员函数中,您需要将您的输入放入临时 arguments 并传递它们,您还应该重命名您的成员set_age等以指示set_first_name他们在做什么。

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.然后你试图 output 使用相同的函数而不再次调用它们,但即使你这样做了,它们也会返回void ,所以什么也没有。 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.看起来你也不知道static在 class 中是什么意思,现在你所有的Student class 实例可能会共享年龄,名字,姓氏和标准,

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

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