在C中重载子类中的方法
发布时间:2020-12-16 03:43:48 所属栏目:百科 来源:网络整理
导读:假设我有一些像这样的代码: class Base { public: virtual int Foo(int) = 0;};class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0;};class Concrete : public Derived { public: double Foo(double);}; 如果我有一个Con
假设我有一些像这样的代码:
class Base { public: virtual int Foo(int) = 0; }; class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0; }; class Concrete : public Derived { public: double Foo(double); }; 如果我有一个Concrete类型的对象,为什么我不能调用Foo(int)? 解决方法
名称查找在重载解析之前发生,因此一旦在Concrete中找到Foo,基类将不会搜索名为Foo的其他方法. Derived中的int Foo(int)由Foo in Concrete隐藏.
你有很多选择. 将呼叫更改为显式. concrete.Derived::Foo(an_int); 在Concrete中添加using声明. class Concrete : public Derived { public: using Derived::Foo; double Foo(double); }; 通过基准引用调用该函数. Derived& dref = concrete; dref.Foo(an_int); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |