繁体   English   中英

重载虚拟 function

[英]Overloading a virtual function

我正在尝试重载虚拟 function,如下所示:

#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;
class Base{
    public:
        virtual void show(int x){
            cout << "Showing int as Base: " << x << endl;
        }
};
class Derived : public Base{
    public:
        using Base::show;
        virtual void show(string s){
            cout << "Showing string as Derived: " << s << endl;
        }
};
int main(){
    Derived x;
    Base& ref = x;
    ref.show(3);
    ref.show(string("hi")/*in case the compiler refuses to implicitly convert const char* to std::string*/);
}

然而,GCC 抱怨error: cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' ,并说note: initializing argument 1 of 'virtual void Base::show(int)'

似乎 gcc 只是忽略了Derived的显示过载。

我怀疑重载和多态性对于编译器来说只是一个有点难以处理,因为这也需要将类型信息存储在 vtable 中,这可能是不可能的。
但是,我应该怎么做才能模仿这种行为呢?

这有效:

#include<iostream>
#include<string>
#include<any>
using std::cout;
using std::endl;
using std::string;
using std::any;
using std::any_cast;
class Base{
    public:
        virtual void show(int x){
            cout << "Showing int as Base: " << x << endl;
        }
        virtual void show(any x) = 0;
};
class Derived : public Base{
    public:
        using Base::show;
        virtual void show(any s) override{
            if(s.type() != typeid(std::string)){
                if(s.type() != typeid(int)){
                    throw "SOME_ERROR_INDICATING_INVALID_FUNCTION_CALL";
                }
                Base::show(any_cast<int>(s));
                return;
            }
            cout << "Showing string as Derived: " << any_cast<string>(s) << endl;
        }
};
int main(){
    Derived x;
    Base& ref = x;
    ref.show(3);
    ref.show(string("hi")/*invokes show(any) override */);
}

但它似乎真的很愚蠢。 还有其他解决方法吗?

编辑:添加virtual void show(string x)=0; 基地是不可取的。 这只是一个 MRE,在实际程序中我有很多派生类,我不想在Base中为每个自定义添加纯虚拟 function。

问题是您通过引用基数 object 调用show ,同时将std::string作为参数传递,但基数 class 没有任何此类方法,因此此调用无法成功。

要解决这个问题,您可以为virtual void show(string s) =0;添加声明。 基地内部 class。

class Base{
    public:
        virtual void show(int x){
            cout << "Showing int as Base: " << x << endl;
        }
        //added this declaration for making it pure virtual
        virtual void show(string s)=0;
};

暂无
暂无

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

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