Making my own toString() method on c++ struct

  • A+
Category:Languages

I'm used to oveerriding the Java toString() method on my own objects in classes, but I'm not sure where I'm going wrong with the following code:

    struct Student {     std::string name;     int age;     double finalGrade;      std::string toString() {         return "Name: " + name + "/n Age: " + age + "/n Final Grade: " + finalGrade;     } }; 

I'm only beginning to learn c++ so any advice would be appreciated

 


You can't add anything you want to a std::string like you can to a Java String. Notably, most objects are not expected to have a toString member function. However, the standard library provides std::to_string which allow you to convert numeric values to an std::string. For example you could wrap the numeric values with a std::to_string to fix your function :

#include <string>  struct Student {     std::string name;     int age;     double finalGrade;      std::string toString() {         return "Name: " +              name +              "/n Age: " +              std::to_string(age) +              "/n Final Grade: " +              std::to_string(finalGrade);     } }; 

Edit : Though this answer explains why what you tried doesn't work, the other answer's solution is the preferred approach.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: