//我需要制作的函数是该类中的to.string(),我不知道该如何制作。这是一个奇怪的函数(不与数学类进行比较。)它返回两种不同类型的值数据类型即(string,integer)的唯一困扰我的是在使(string to.string())function后分配了一个变量// function的返回值类似于
[年龄,名字,姓氏,标准](输出中不带方括号和逗号)
p.s =需要一个不使用 vector 头的简单函数。
#include <iostream>
#include <sstream>
using namespace std;
class Student{
public :
void set_age(int no){
age_no=no;
}
void set_standard(int no){
std_no=no;
}
void set_first_name(string identity){
name_letter=identity;
}
void set_last_name(string identity2){
last_name_letter = identity2;
}
int get_age(){
return age_num;
}
int get_standard(){
return std_no;
}
string get_first_name(){
return name_letter;
}
string get_last_name(){
return last_name_letter;
}
private :
int age_no;
int std_no;
string name_letter;
string last_name_letter;
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
cout << st.to_string();
return 0;
}
最佳答案
如果要创建格式为age, first_name, last_name, standard
的字符串,则可以执行以下操作
class Student
{
public:
...
std::string to_string() const;
...
};
std::string Student::to_string() const
{
return std::to_string(get_age()) + ", " +
get_first_name() + ", "
get_last_name() + ", "
std::to_string(get_standard());
}
顺便说一句,我建议例如将所有的getter函数设为const
int get_age() const;
这表示该方法不会突变或修改类成员变量的任何值。
关于c++ - 可以在下面定义一个更简单的函数-(to.string()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64279056/