0

I created a class called person with two members name and age then I created two objects of that

class p1 and p2 and then I added them to a vector. I tried then to print them but could not.

this my code:

class Person{
public: 
    string name; 
    int age; 
}; 



int main(){
    Person p; 
    vector <Person> vector; 
    p.name = "Vitalik"; 
    p.age = 29; 
    Person p2; 
    p2.name = "Bueterin"; 
    p2.age = 50; 
    vector.push_back(p); 
    vector.push_back(p2); 
    
    for(int i = 0; i < vector.size(); i++){
        cout << vector[i] << endl; 
    }

    

    return 0; 
}

I tried multiple ways to loop through the vector and print the elements but I keep getting this message:

 error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'std::__vector_base<Person, std::allocator<Person> >::value_type' (aka 'Person'))
        cout << vector[i] << endl; 
brah79
  • 37
  • 5
  • 3
    The compiler can't figure out how you want to print a `Person` on its own; you need to implement `std::ostream& operator<<(std::ostream&, const Person&)` yourself. See a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). – molbdnilo Nov 15 '22 at 09:36

2 Answers2

3

You can implement operator<< or just write something like this:

cout << vector[i].name << ": " << vector[i].age << endl;

cout doesn't know how to print this object by default.

Vslav
  • 81
  • 5
1

you should implement an operator<< method
How to properly overload the << operator for an ostream?
https://en.cppreference.com/w/cpp/language/operators

jsofri
  • 227
  • 1
  • 10
  • 1
    A answer should not only/mainly consist of links. If you find that another post on SO answers the question, you should instead vote to close as duplicate or leave a link as comment. – Lukas-T Nov 15 '22 at 09:44