c – 重载超类的功能
发布时间:2020-12-16 06:01:02 所属栏目:百科 来源:网络整理
导读:C标准有什么东西阻止我超载超级类的功能吗? 从这对课程开始: class A { // super class int x;public: void foo (int y) {x = y;} // original definition};class B : public A { // derived class int x2;public: void foo (int y,int z) {x2 = y + z;} /
C标准有什么东西阻止我超载超级类的功能吗?
从这对课程开始: class A { // super class int x; public: void foo (int y) {x = y;} // original definition }; class B : public A { // derived class int x2; public: void foo (int y,int z) {x2 = y + z;} // overloaded }; 我可以轻松调用B :: foo(): B b; b.foo (1,2); // [1] 但是如果我尝试调用A :: foo()… B b; b.foo (12); // [2] …我得到一个编译错误: test.cpp: In function 'void bar()': test.cpp:18: error: no matching function for call to 'B::foo(int)' test.cpp:12: note: candidates are: void B::foo(int,int) 只是为了确保我没有丢失任何东西,我改变了B的功能的名称,以便没有超载: class B : public A { int x2; public: void stuff (int y,int z) {x2 = y + z;} // unique name }; 现在我可以使用第二个例子来调用A :: foo(). 这是标准吗我用g 解决方法
您需要在B类定义中使用using声明:
class B : public A { public: using A::foo; // allow A::foo to be found void foo(int,int); // etc. }; 没有使用声明,编译器在名称查找期间找到B :: foo,并且有效地不搜索具有相同名称的其他实体的基类,因此未找到A :: foo. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |