Error C ++ operator << <<

I have a question about homework.

I have two classes. One is called ticket.cpp and the other is TicketOrder.cpp

Home is located within ticket.cpp.

I am using the g ++ compiler on Linux.

I am trying to print a TicketOrder object vector called orders, but it causes the following error:

ticket.cpp: 57: error: no match for 'operator <<in' std :: cout <orders. std :: vector <_Tp, _Alloc> :: operator [] with _Tp = TicketOrder, _Alloc = std :: allocator '

Here is my code:

ticket.cpp

 #include <iostream> #include <vector> #include <limits> #include <cctype> #include "TicketOrder.cpp" using namespace std; int main () { int numberoftickets=0; string input2; char input3; int profit=0; vector <TicketOrder> orders; int atotalmoney=0; int btotalmoney=0; int ctotalmoney=0; int dtotalmoney=0; int etotalmoney=0; do { cout << "\nPick a ticket that you would like to buy: \n\n"; cout << "(A) Students without an activity card: $2.00 \n"; cout << "(B) Faculty and staff: $3.00 \n"; cout << "(C) USC alumni: $5.00 \n"; cout << "(D) UCLA students and alumni: $20.00 \n"; cout << "(E) Everyone else: $10.00 \n"; cin >> input3; if (input3=='A') { cout << "How many tickets do you wish to buy? " <<endl; if (numberoftickets >0) { TicketOrder order; order.setQuantity(numberoftickets); order.setType(input3); orders.push_back(order); for (int i=0; i< orders.size(); i++) { cout << orders[i]; } } } else { cout << "Sorry did not recognize input, try again. " << endl; } } while (input3 != 'S'); 

TicketOrder.cpp:

 #include <iostream> using namespace std; class TicketOrder { public : //Getters int getQuantity() const { return quantity; } char getType() const { return type; } //Setters void setQuantity (int x) { quantity=x; } void setType(char y) { type =y; } private: char type; char quantity; }; 
+6
source share
3 answers

As the compiler clumsily tries to explain, the code is missing operator<< for the TicketOrder class.

 class TicketOrder { public: friend std::ostream& operator<<(std::ostream& os, TicketOrder const& order) { os << "Type: " << type << ", quantity: " << quantity; return os; } char type; int quantity; }; 

(Note: you probably want to change quantity to int .)

+7
source

You must add the <<operator as a friend to be able to print values ​​from your TicketOrder objects using cout. Further reading

0
source

You are trying to use the <operator on the cout object and TicketOrder . It is undefined. You must use the TicketOrder object to first generate a string and then output it via cout . Either this, or you can define an <operator for the TicketOrder class, as described in one of the other two answers.

0
source

Source: https://habr.com/ru/post/907916/


All Articles