我需要 C++ 结构方面的帮助
I need help in structure in c++
该程序将采用对象名称"st"的结构,将采用年龄,然后是名字和姓氏,而不是标准
但是说的是这个错误
(main.cpp:33:10: 错误:无效使用非静态成员函数'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;
}
现在真的不清楚您要用您的代码实现什么。
首先,你的问题是因为试图将一些输入放入带参数的成员函数中,你需要将你的输入放入临时参数中并传递它们,你还应该将你的成员函数重命名为 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);
然后你试图使用相同的函数输出它们而不再次调用它们,但即使你这样做了,它们 return void
,所以什么也没有。您需要一组不同的成员函数来访问这些变量。
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';
}
您似乎还不知道 class 中的 static
是什么意思,现在 Student
class 的所有实例都将共享年龄,first_name, last_name 和标准,这可能不是你提到的。
该程序将采用对象名称"st"的结构,将采用年龄,然后是名字和姓氏,而不是标准
但是说的是这个错误
(main.cpp:33:10: 错误:无效使用非静态成员函数'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;
}
现在真的不清楚您要用您的代码实现什么。
首先,你的问题是因为试图将一些输入放入带参数的成员函数中,你需要将你的输入放入临时参数中并传递它们,你还应该将你的成员函数重命名为 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);
然后你试图使用相同的函数输出它们而不再次调用它们,但即使你这样做了,它们 return void
,所以什么也没有。您需要一组不同的成员函数来访问这些变量。
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';
}
您似乎还不知道 class 中的 static
是什么意思,现在 Student
class 的所有实例都将共享年龄,first_name, last_name 和标准,这可能不是你提到的。