以指针作为参数重载 ostream << 运算符导致输出内存地址

Overloading ostream << operator with pointer as parameter resulting with memory adress on output

我在重载 ostream 运算符时遇到了一些问题。有3个classes,abstract base class Packet 另一个abstract class Sequence继承自Packet和class TimeHistory继承自Sequence.

class Packet
{
//some stuff
};

template <typename T = double>
class Sequence : public Packet
{
std::vector<T> buffer;
//some other stuff
}

template <typename T = double>
class TimeHistory : public Sequence<T>
{
template <typename X>
    friend std::ostream &operator<<(std::ostream &out, Packet *A);
//another stuff
}

以及打印对象中数据的友元函数

std::ostream &operator<<(std::ostream &out, Packet *A)
{
    TimeHistory<T> *th = dynamic_cast<TimeHistory<T> *>(A);
    out << th->device
        << th->description
        << th->channelNr;
    for (auto in : th->buffer)
        out << in << std::endl;
    return out;
} 

当我创建 class 的实例时:

std::unique_ptr<Packet> channel1 = std::make_unique<TimeHistory<double>>(/*some constructor stuff*/);

并调用函数

  std::cout<<(channel1.get());

我在输出中只得到一个内存单元地址:0x560c8e4f1eb0 有人能指出我做错了什么吗?

std::unique_ptr::get 将 return 指向托管对象的指针。如果您想获得对托管值的引用,请使用

std::cout<< *channel1;

要为抽象 class 重载 operator<<,您可以使用引用而不是指针:

friend std::ostream &operator<<(std::ostream &out, Packet &A);