0

I was wondering how I can print an instance of a class I've created to console?

The class I've created:

class Person
{
private:
    string surname;
    string forename;
    int age;
public:
    Person(string surname, string forename, int age) :surname(surname), forename(forename), age(age) { }
    void getSurname();
    void getForename();
    void getAge();
};

Creating the instance:

int main()
{    
    std::string testSurname{ "RandomSurname" };
    std::string testForename{ "RondomForename" };
    std::string testAge{ "1" };

    int testAgeInt = std::stoi(testAge);
    Person somePerson{ testSurname, testForename, testAgeInt };
}

How can I print that last line to console?

I've attempted using the obvious:

cout << somePerson;

But I get a "no operator '<<' matches these operands" error.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • What have you tried? How did your attempt work, or not work? And if you get it to work for a single object, then printing out an array is just the same, wrapped in a loop. Please take some time to [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Jun 26 '17 at 00:54
  • Just make the constructor print all the fields to `std::cout`. If you want reflection, C++ doesn't have it. Use something like Go instead. – Henri Menke Jun 26 '17 at 00:56
  • @HenriMenke What advise is that... – Stargateur Jun 26 '17 at 00:59
  • 1
    Perhaps you need [a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? Because it should explain both how to print individual members (either directly or through function calls) as well as how to overload the `<<` operator to allow what you have tried. – Some programmer dude Jun 26 '17 at 00:59
  • 1
    Regarding the second question: you could use `std::vector arr;` to store instances of the class. – lawful_neutral Jun 26 '17 at 01:01
  • possible duplicate of [https://stackoverflow.com/questions/2981836/how-can-i-use-cout-myclass](https://stackoverflow.com/questions/2981836/how-can-i-use-cout-myclass) ? – Randolf Jun 26 '17 at 01:13

0 Answers0