Question: Consider number.cc. It creates a class called Number thats a wrapper around an int. 1) How is it that < < works for Number, even
Consider number.cc. It creates a class called Number thats a wrapper around an int.
1) How is it that << works for Number, even though operator<< wasnt defined for this class?
2) Consider operator>>. It doesnt check for failure. And, yet, it works properly for: valid numeric input, end of input, incorrect input. How can this be?
3) Now, improve operator>> so that it works properly for input such as one, two, three, four, and five, as well as working for all traditional numeric input that worked before. Consider using ios::clear
#include#include using namespace std; class Number { public: Number() = default; Number(const Number &) = default; Number(int v) : value(v) {} Number &operator=(int n) { value = n; return *this; } operator int() const { return value; } private: int value = 0; // default value unless otherwise given }; istream &operator>>(istream &is, Number &rhs) { int n; is >> n; rhs = n; return is; } int main() { Number n = 666; istringstream ss("12 34 three 789 five"); while (ss >> n) cout << n << ' '; cout << ' '; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
