所以在我的程序中我有一些类 - Button、Window 和 WindowButton。 Button 仅由文本组成,Window - 由按钮和坐标 (x,y) 组成,而 WindowButton 由一个 Window 组成。 在 WindowButton 中,我像这样重载了 << 运算符:
ostream& operator<<(ostream& out, WindowButton& ref)
{
ref.print();
return out;
}
打印函数的样子:
void WindowButton::print()
{
theWindow->print();
}
和窗口打印函数,在窗口类中:
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;
}
主要内容:
WindowButton *test = new WindowButton();
cout << endl << test;
test->print();
最后一行提供了正确的输出,但第二行只提供了一个内存地址。我究竟做错了什么?一切都应该工作正常,因为 test->print();工作正常。
最佳答案
您正在将指针传递给需要 & 的运算符<<。
cout << endl << *test;
你也可以做到:
ostream& operator<<(ostream& out, const WindowButton& ref){
假设 print 实际上没有修改。
但是,更大的问题是您为什么要使用 cout
ostream 来触发打印到 theWindow
- 这些似乎是(虽然不是)逻辑上断开连接的进程.您可以将给定的流传递到 Window::print:
void Window::print(ostream& stream) {
并使用该流代替 cout
。这避免了将 cout
硬编码到 Window::print()
中。
关于C++重载运算符<<输出地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12450949/