C++重载运算符<<输出地址

标签 c++ overloading

所以在我的程序中我有一些类 - 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/

相关文章:

C++ WxWidgets : Redirecting Stdout to a wxTextCtrl across mulitple threads

c++:在网格上找到离查询点最近的点

c++ - 这是不好的做法吗? C++

java - JNI C++ DLL - 'UnsatisfiedLinkError: %1 is not a valid Win32 application'

java - Java 中泛型的方法重载和参数

c# - 术语 - 在不同的命名空间中声明方法是否算作重载

c++ - new运算符和构造函数参数的执行顺序

java - 有人可以帮助我了解我的战斗机类别中的攻击方法吗

c++ - (函数)模板的 C++ 非类型参数是否有序?

c++ - 多个默认构造函数