c++ - 可以在下面定义一个更简单的函数-(to.string())

标签 c++ string class

//我需要制作的函数是该类中的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/

相关文章:

c++ - 声明一个二维 vector

c - 使用函数反转 C 中的字符串

ios - 在 View Controller 之间设置 UIImageView.image

c++ - 将 const char* 赋值给 char 时类型不兼容

c++ - 创建模板约束的 C++ 工厂

c++ - 如何避免重复的模板特化?

php 内爆(101)带引号

python拆分矢量格式字符串

c++ - 没有类(class)类型

c++ - 如何识别最后一个变量参数?