简体   繁体   English

C ++模板和继承,函数未在派生类中替换

[英]C++ template and inheritance, function not replaced in derived class

Here I attached a minimal case, where in child class, cmp will replace the one in parent class, but it doesn't work, it always calls the one from the parent 在这里我附加了一个最小的情况,在子类中, cmp将替换父类中的一个,但它不起作用,它总是调用父类中的一个

#include <iostream>

template <typename T>
class A
{
    public:
        void tell(T a, T b)
        {
            std::cout << (cmp (a, b) ? a : b) << " is better" << std::endl;
        }
    protected:
        bool cmp (T & a, T & b)
        {
            return a > b;
        }
};

template <typename T>
class B: public A<T>
{
    protected:
        bool cmp (T & a, T & b)
        {
            return a < b;
        }
};

int main ( int argc , char **argv ) 
{
    B<int> b;
    // should be: 3 is better here
    b.tell(5, 3);
    return 0;
}

You must declare polymorphic functions virtual . 您必须将多态函数声明为virtual Otherwise you will not get polymorphic behaviour 否则你不会得到多态行为

virtual bool cmp (T & a, T & b)

Your cmp function must be declared virtual in A . 您的cmp函数必须在A声明为virtual

protected:
    virtual bool cmp (T & a, T & b)
    {
        return a > b;
    }

It will implicitly remain virtual in derived classes, although I'd explicitly declare cmp virtual in B as well, for clarity's sake. 它将在派生类中隐式保持虚拟,尽管为了清楚起见我也明确地在B声明了cmp virtual。

你应该让cmp成为基类中的虚函数:

virtual bool cmp (T & a, T & b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM