Reputation: 74
I don't know why cout << da << '\n'
works fine,but std::cout << next_Monday(da) << '\n'
went wrong. Why the direct Date
object can output, but the return Date
can't.
Why overloaded operator <<
works sometimes but other times doesn't.
here is my code..
#include <iostream>
#include <stdlib.h>
struct Date {
unsigned day_: 5;
unsigned month_ : 4;
int year_: 15;
};
std::ostream& operator<<(std::ostream& out,Date& b)
{
out << b.month_ << '/' << b.day_ << '/' << b.year_;
return out;
}
std::istream& operator>>(std::istream& in,Date& b);
Date next_Monday(Date const &d);
int main()
{
Date da;
std::cin >> da;
std::cout << da << '\n';
std::cout << next_Monday(da) << '\n';
return 0;
}
this is what clang said: (I use g++ to invoke)
excercise19DateManipulate.cpp:114:18: error: invalid operands to binary
expression ('ostream' (aka 'basic_ostream<char>') and 'Date')
std::cout<< next_Monday(da) <<'\n';
~~~~~~~~^ ~~~~~~~~~~~~~~~
Upvotes: 2
Views: 103
Reputation: 1
You never defined the "next_Monday()" function as far as I can see, you only declared it.
Upvotes: -2
Reputation: 227370
Because you can't bind a temporary to a non-const lvalue reference. Change the operator to take a const
reference:
std::ostream& operator<<(std::ostream& out, const Date& b)
Upvotes: 6