Reputation: 33
My code keeps giving me error Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'const bus')
Is this a case of the most vexing parse? if so how to fix it. I am trying to print out objects stored in vector. std::vector<bus> v = {}
is my vector to contain the object whereas bus
is my class
#include <iostream>
#include <vector>
class bus{
public:
int carNum, releaseYear;
};
int temp1, temp2;
void print(std::vector<bus> const &input)
{
for (auto it = input.cbegin(); it != input.cend(); it++)
{
std::cout << *it << ' '<< std::endl;
}
}
int main()
{
bus bus1;
bus1.carNum = 0;
bus1.releaseYear = 0;
bus bus2;
bus2.carNum = 0;
bus2.releaseYear = 0;
// Create a vector containing objects
std::vector<bus> v = {};
// Add two more integers to vector
std::cout<<"enter number"<<std::endl;
std::cin>>temp1;
temp1 = bus1.carNum;
std::cout<<"enter year"<<std::endl;
std::cin>>temp2;
temp2 = bus1.releaseYear;
v.push_back(bus1);
print(v)
}
Upvotes: 0
Views: 54
Reputation: 60228
There is no vexing parse here. You simply need to overload the stream insertion operator for the bus
type. Since bus
only has public data members, this can be a non-friend function:
std::ostream& operator<<(std::ostream& stream, bus const& b)
{
stream << "#" << b.carNum << " Year" << b.releaseYear;
return stream;
}
You can of course, format your output however you want.
Upvotes: 2