如何在C++ Student类中实现简易的to_string()成员函数
get_age() & Implementing to_string() Hey there! Let's work through your two main issues with the Student class—fixing the get_age() variable name bug and building the to_string() member function that combines different data types into a comma-separated string.
1. Fixing the get_age() Variable Name Error
First, let's tackle the simple bug in your get_age() function. You mentioned it should return age_no instead of age_num—so all you need to do is correct the return variable name in that method.
Here's what the corrected method looks like:
int get_age() const { return age_no; // Fixed: was returning age_num before }
2. Implementing the to_string() Member Function
To create a comma-separated string from age (int), first_name (string), last_name (string), and standard (int), we need to convert the integer values to strings first, then concatenate everything with commas.
We'll use std::to_string() (from the <string> header) to turn integers into strings—no need for vectors, which fits your requirement.
Here's how to write the full Student class with the required function:
#include <string> // Don't forget this header for string operations! class Student { private: int age_no; std::string first_name; std::string last_name; int standard; public: // Corrected get_age() method int get_age() const { return age_no; } // Assume you have these setter/getter functions for other members (adjust as needed) void set_age(int a) { age_no = a; } std::string get_first_name() const { return first_name; } void set_first_name(std::string fn) { first_name = fn; } std::string get_last_name() const { return last_name; } void set_last_name(std::string ln) { last_name = ln; } int get_standard() const { return standard; } void set_standard(int s) { standard = s; } // The required to_string() member function std::string to_string() const { // Convert integers to strings, then concatenate all parts with commas return std::to_string(age_no) + "," + first_name + "," + last_name + "," + std::to_string(standard); } };
How This Works:
std::to_string(age_no)andstd::to_string(standard)convert your integer values intostd::stringtypes, so they can be combined with the existing string members.- The
+operator chains all the parts together: converted age string → comma → first name → comma → last name → comma → converted standard string. - The result is a single, clean comma-separated string with no extra brackets, just like you need.
Testing the Function
If you want to verify this works, here's a quick test snippet:
#include <iostream> int main() { Student s; s.set_age(17); s.set_first_name("John"); s.set_last_name("Doe"); s.set_standard(12); std::cout << s.to_string() << std::endl; // Output: 17,John,Doe,12 return 0; }
内容的提问来源于stack exchange,提问作者user14400886

