调用基类的重载方法 [英] Calling base class's overloaded method

查看:109
本文介绍了调用基类的重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

  #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 function Print() of the superclass. Therefore, the compiler will not see A::Print() and will try to invoke B::Print(), complaining that an int could not be converted into a string.

To bring A::Print() into the overload set, you can introduce a using 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.

这篇关于调用基类的重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆