So in my program I have some classes – Button, Window and WindowButton. Button consists only of text, Window – of a button and coordinates(x,y), and WindowButton consists of a Window.
In WindowButton, I have overloaded the << operator like this:
ostream& operator<<(ostream& out, WindowButton& ref)
{
ref.print();
return out;
}
Where the print function looks like:
void WindowButton::print()
{
theWindow->print();
}
And the window print function, in window class:
void Window::print()
{
char* buttonText = button->getText();
char* theText = new char[strlen(buttonText)+1];
strcpy(theText, buttonText);
cout << endl << "Window with coordinates (" << this->coord.x << "," << this->coord.y << ") , and button text \"" << theText << "\"" << endl;
}
In main:
WindowButton *test = new WindowButton();
cout << endl << test;
test->print();
The last line provides the right output, but the second line provides just a memory adress. What am I doing wrong? Everything should be working fine, because the test->print(); works fine.
You are passing a pointer to operator<< which expects a &.
You might also make it:
Which assumes print doesn’t actually modify.
But, the bigger question is why are you using the
coutostream to trigger printing totheWindow— these appear to be (though aren’t) logically disconnected processes. You could pass the given stream into Window::print:and use that stream in place of
cout. This avoids hard-codingcoutintoWindow::print().