在 C++ 中重载运算符 << 时无法清除垃圾

Can't get rid of trash while overloading operator << in C++

class point //declaration of class
{
    private:
    int x, y;
    friend std::ostream &operator << (std::ostream &input, point &p);
    public:
    //constructors and some other methods
};

//definition of overloading <<
std::ostream &operator << (std::ostream &input, point &p)
{
    input << std::cout << "x = " << p.x << " y = " << p.y << " ";
    return input;
}

它有效,但当我使用它时

std::cout << object;

它在我的文字前显示了一些垃圾:

062ACC3E8x = 1 y = 22

所以062ACC3E8X是经常出现的东西。如果我重新启动我正在处理的 Visual Studio 是不同的,所以我想这是一些内存地址。如何摆脱它?我的代码中是否有遗漏或错误?

您正在将 std::cout 传递到您的输出流中。将您的代码更改为:

//definition of overloading <<
std::ostream &operator << (std::ostream &input, point &p)
{
    input << "x = " << p.x << " y = " << p.y << " ";
    return input;
}

你输出了一些地址,因为 std::ostreamimplicit void* conversion operator

1) Returns a null pointer if fail() returns true, otherwise returns a non-null pointer. This pointer is implicitly convertible to bool and may be used in boolean contexts.

应该只是

input << "x = " << p.x << " y = " << p.y << " ";