问题描述
我有这个代码:
#include< iostream>
#include< string>
using namespace std;
class A {
public:void Print(int i){cout<< i;}
};
class B:public A {
public:void Print(string s){cout<< s;}
};
int main(){
B bInstance;
bInstance.Print(1);
return 0;
}
这给我一个错误:
错误:从'int'到'const char *'无效转换[-fpermissive]
意味着它试图调用B的打印,而不考虑继承的超载。但是,A的Print应该可以由B实例调用。事实上,如果我改变对
bInstance.A :: Print(1)的调用;
然后它编译没有任何错误,但我想避免每次都要写类scope 。
有没有办法告诉编译器我试图调用基类的重载函数?解决方案您的子类中的
Print()
成员函数隐藏成员函数Print()
超类。因此,编译器不会看到A :: Print()
,并尝试调用B :: Print()
,抱怨int
无法转换为字符串。
要将
A :: Print()
带入重载集,您可以引入使用
声明:class A {
public:
void Print (int i){cout<<< i;}
};
class B:public A {
public:
using A :: Print;
// ^^^^^^^^^^^^^^^
void Print(string s){cout<< s;}
};
这是一个您的代码在必要修改后可以正常工作。
I have this code:
#include <iostream> #include <string> using namespace std; class A { public: void Print(int i) {cout<<i;} }; class B : public A { public: void Print(string s) {cout<<s;} }; int main() { B bInstance; bInstance.Print(1); return 0; }
This gives me an error:
error: invalid conversion from 'int' to 'const char*' [-fpermissive]
meaning it is trying to call B's Print without considering the inherited overload. But, A's Print should be callable by a B instance. In fact, if I change the call to
bInstance.A::Print(1);
then it compiles without any errors, but I wanted to avoid having to write the class scope operator each time.Is there a way to tell the compiler I am trying to call the base class's overload of the function?
解决方案The
Print()
member function in your subclass hides the member functionPrint()
of the superclass. Therefore, the compiler will not seeA::Print()
and will try to invokeB::Print()
, complaining that anint
could not be converted into a string.To bring
A::Print()
into the overload set, you can introduce ausing
declaration:class A { public: void Print(int i) {cout<<i;} }; class B : public A { public: using A::Print; // ^^^^^^^^^^^^^^^ void Print(string s) {cout<<s;} };
Here is a live example of your code working after the necessary modifications.
这篇关于调用基类的重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!