c++ - 多态和继承打印

标签 c++ inheritance polymorphism

我对多态性和继承有疑问。 父类是:

class IIR_filter {

private:
    double* a_;
    double* b_;
    unsigned int order_;

    void reverseArray(double* source, double* destination, unsigned int size);

public:
    IIR_filter();
    IIR_filter(double* a, double* b, unsigned int order);   //c'tor
    IIR_filter(const IIR_filter& filter);                   //copy c'tor
    virtual ~IIR_filter();                                          //d'tor

    virtual void filter(double* inputX, double* outputY, unsigned int size);

    virtual void zeroPhaseFilter(double* inputX, double* outputY, unsigned int size);

    friend ostream& operator<<(ostream& lhs, const IIR_filter& rhs);

protected:
    double filterSample(unsigned int indexY, double* outputY,double newSample, Queue<double>& filter);
    double getElementA(unsigned int index) const;
    double getElementB(unsigned int index) const;
    unsigned int getOrder() const;
    virtual void print(ostream& lhs, const IIR_filter* rhs)const;
};

and the cpp relevant functions are:

ostream& operator<<(ostream& lhs, const IIR_filter& rhs){
    std::cout << "IIR filter: " << std::endl;
    rhs.print(lhs, &rhs);
    return lhs;
    }

派生类是:

class FIR_filter : public IIR_filter {

public:
    FIR_filter(double* b, unsigned int order);              //c'tor
    friend ostream& operator<<(ostream& lhs, FIR_filter* rhs);


};

cpp函数是:

ostream& operator<<(ostream& lhs, FIR_filter* rhs){
lhs << "FIR filter: \n";
rhs->print(lhs, rhs);
return lhs;
}

当然还有 IIR_filter 类中的 print 函数,但它太长且与我的观点无关。

问题是: 当我从派生类的对象调用打印函数 (operator<<) 时,打印是从父类完成的,因此我得到的不是标题“FIR 过滤器”,而是标题“IIR 过滤器”。 我尝试了很多方法但没有成功。 请帮忙。 谢谢,冉。

最佳答案

您应该将 header 的写入移动到虚拟 print 内的流中函数,并在派生类中创建一个合适的覆盖。您可能还想重构代码以获得虚拟 print_header在非虚拟内部调用的函数 print ,因为您目前没有在派生类中覆盖它。

顺便说一句,你有不一致 - 一个 operator<<正在接受对 const 对象的引用,另一个正在接受指针。但即使你统一了你的约定,operator<<仍然不是虚拟的,因此它无法在运行时确定对基类型的引用(或指针)是否确实指向派生对象。这意味着,在当前状态下,它将(并且应该)始终打印 "IIR filter"标题。

关于c++ - 多态和继承打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954543/

相关文章:

c++ - opencv c++ 中的鼠标事件

java - 继承到底是如何运作的?

java - 子类的对象创建是否创建父类(super class)的对象,如果是,是否可以在子类中访问它?

c++ - 如何从 C++ 中的基类构造函数调用派生类方法?

c++ - 派生模板类

c++ - OpenGL/SDL - 无法进行线路加载

c++ - 使用 boost::ref 传递对取值函数的引用

c++ - C++ 中的数组声明、大小定义和销毁

c++ - C++中的继承和指针

c++ - std::unique_ptr<T[]> 带有派生对象数组,使用已删除函数