我为什么要使用“使用"?关键字来访问我的基类方法?

2021-12-12 00:00:00 oop inheritance using c++

我写了下面的代码来解释我的问题.如果我注释第 11 行(使用关键字using"),编译器不会编译文件并显示以下错误:invalid conversion from 'char' to 'const char*'.在Son类中似乎没有看到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
", *how ); }
};

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

推荐答案

在派生类中声明的 action 隐藏了在基类中声明的 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.

相关文章