C++ Assume the existence of a Window class with integer data members width and h
ID: 3867323 • Letter: C
Question
C++
Assume the existence of a Window class with integer data members width and height. Overload the << operator for the Window class-- i.e., write a nonmember ostream-returning function that accepts a reference to an ostream object and a constant reference to a Window object and sends the following to the ostream: 'a (width x height) window' (without the quotes and with width and height replaced by the actual width and height of the window. Thus for example, if the window had width=80 and height=20, << would send 'a (80 x 20) window' to the ostream object.) Don't forget to have the function return the proper value as well. Assume the operator has been declared a friend in the Window class.
Explanation / Answer
Below is your function
ostream &operator << (ostream &strm) const
{
return strm << "a " << "("<<obj.width<<"X"<<obj.height<<")" << " window" << endl;
}
you can call this via
cout<<wind;
where wind is object of Window class
Sorry I missed one object here .. Here is your updated answer
ostream &operator << (ostream &strm, const Window& obj)
{
return strm << "a " << "("<<obj.width<<"X"<<obj.height<<")" << " window" << endl;
}
Check this one: -
#include <iostream>
using namespace std;
class Window {
ostream &operator << (ostream &strm)
{
return strm << "a " << "("<<this->width<<"X"<<this->height<<")" << " window" << endl;
}
Window(int w, int h) : width(w), height(h) {}
private:
int width, height;
};
One more update, your code wants operator function as a friend function, but your code is not implementing it like this .. The code must be linke this below: -
#include <iostream>
using namespace std;
class Window {
public:
friend ostream &operator << (ostream &strm,const Window& obj)
{
return strm << "a " << "("<<obj.width<<"X"<<obj.height<<")" << " window" << endl;
}
Window(int w, int h) : width(w), height(h) {}
private:
int width, height;
};
int main() {
Window w(80,90);
cout<<w;
return 0;
}
Output:-
a (80X90) window
--------------------------------
Process exited after 0.3112 seconds with return value 0
Press any key to continue . . .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.