为什么`operator<<`不能在指向派生类型的成员上工作?

时间:2018-06-04 09:33:37

标签: c++ output operator-overloading

我有一个类Base,其成员指向派生类型Derv

class Derv;

class Base
{
protected:
    std::vector<std::shared_ptr<Derv>> opnds;
    ...
}

派生类看起来像这样:

#include "Base.h"

class Derv:
    public Base
{
...
}

现在,我想通过序列化cout中的项目Base所有opnds和派生类型。我读到类似以下内容的标准方法(因为我可能希望覆盖其他派生类的序列化)。我加入了Base.h

friend std::ostream &operator<<(std::ostream &os, math_struct const &m);
virtual void serialize(std::ostream& os) const;

Base.cpp我实施了:

#include <string>

void Base::serialize(std::ostream& os) const
{
    for (std::size_t i = 0; i < this->opnds.size(); ++i) {
        os << ", " << *this->opnds[i]; // Error: no operator "<<" matches these operands
    }
}

std::ostream& operator<<(std::ostream &os, math_struct const &m) {
    m.serialize(os);
    return os;
}

<<序列化中Base::serialize的递归应用不起作用。它似乎与基类成员中引用的派生类有关。我负责std::vector<std::shared_ptr<Base>> opnds的早期版本工作正常。

我是C ++的新手,所以我可能会遇到一些基本的错误......

1 个答案:

答案 0 :(得分:1)

在定义Derv之前,请检查您是否定义了serialize,否则编译器无法知道,Derv可以转换为Base

以下内容应该:

#include <iostream>
#include <memory>
#include <vector>

class Base;
class Derv;


std::ostream& operator << (std::ostream& out, const Base&);


class Base
{
public:
    void serialize(std::ostream& os) const;

protected:
    std::vector<std::shared_ptr<Derv>> opnds;
};

// class Derv must be _defined_ before defining the functon Base::serialize!

class Derv : public Base { };


void Base::serialize(std::ostream& os) const
{
    for (std::size_t i = 0; i < this->opnds.size(); ++i) {
        os << ", " << *this->opnds[i];
    }
}

std::ostream& operator << (std::ostream& out, const Base&)
{
    out << "operator called" << std::endl;
    return out;
}