试图重载cout <<运算符,但它不起作用

use*_*252 1 c++ overloading operator-keyword

我在这里剪掉了我班上不相关的部分.我不知道我做错了什么,只是想尝试能够cout <<对象.

#include <iostream>

class Snipped
{

    public:
        friend std::ostream& operator<<(std::ostream& os, const Snipped& s);

    protected:
    private:
};

std::ostream& operator<<(std::ostream& os, const Snipped& s)
{
    os << "test";
    return os;
}

int main(int argc, char* argv[])
{
    Snipped* s = new Snipped();

        std::cout << s << std::endl << s;

    delete s;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

预期产量:

test
test
Run Code Online (Sandbox Code Playgroud)

实际产量:

0x12ae20
0x12ae20  (random memory location?)
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 8

std::cout << s << std::endl << s;      
Run Code Online (Sandbox Code Playgroud)

您正在<<使用地址呼叫,您需要使用类型的对象来调用它Snipped.
上面的代码行不会调用重载的运算符函数,因为重载函数的参数不匹配.

你需要打电话:

std::cout << *s << std::endl << *s;      
Run Code Online (Sandbox Code Playgroud)

这可以确保<<调用重载的操作符函数,因为参数与之匹配.


kfm*_*e04 6

尝试

std::cout << *s << std::endl; 
Run Code Online (Sandbox Code Playgroud)

顺便说说,

std::cout << s << std::endl; 
Run Code Online (Sandbox Code Playgroud)

并不是一个随机的内存位置.

在这种情况下,它是堆上的实际内存地址.

您实际上可以使用该地址来检查对象的身份.

这在调试或实际代码中很有用.例如,如果你看一下赋值运算符,你会经常看到:

class Foo
{
  Foo& operator=( const Foo& foo )
  {
    // use the identity principle 
    if ( &foo==this )
      return *this;  // so I don't waste CPU cycles copying to myself

    // ...really do copy here
    return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)