为什么我应该使用“使用”关键字访问我的基类方法? [英] Why should I use the "using" keyword to access my base class method?

查看:181
本文介绍了为什么我应该使用“使用”关键字访问我的基类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码为了解释我的问题。如果我评论第11行(使用关键字使用),编译器不编译该文件并显示此错误:从'char'到'const char *'无效转换。看起来没有看到中的 Parent 类的方法 void action(char)类。

I wrote the below code in order to explain my issue. If I comment the line 11 (with the keyword "using"), the compiler does not compile the file and displays this error: invalid conversion from 'char' to 'const char*'. It seems to not see the method void action(char) of the Parent class in the Son class.

为什么编译器这样做?或者我做错了什么?

Why the compiler behave this way? Or have I done something wrong?

class Parent
{
    public:
        virtual void action( const char how ){ this->action( &how ); }
        virtual void action( const char * how ) = 0;
};

class Son : public Parent
{
    public:
        using Parent::action; // Why should i write this line?
        void action( const char * how ){ printf( "Action: %c\n", *how ); }
};

int main( int argc, char** argv )
{
    Son s = Son();
    s.action( 'a' );
    return 0;
}


推荐答案

action 隐藏在基类中声明的操作。如果在 Son 对象上使用 action ,编译器将搜索 Son中声明的方法,找到一个名为 action 的,并使用它。它不会继续在基类的方法中搜索,因为它已经找到了匹配的名称。

The action declared in the derived class hides the action declared in the base class. If you use action on a Son object the compiler will search in the methods declared in Son, find one called action, and use that. It won't go on to search in the base class's methods, since it already found a matching name.

然后,该方法不匹配调用的参数,您会收到错误讯息。

Then that method doesn't match the parameters of the call and you get an error.

另请参阅 C ++

See also the C++ FAQ for more explanations on this topic.

这篇关于为什么我应该使用“使用”关键字访问我的基类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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