Why should I use the quot;usingquot; keyword to access my base class method?(我为什么要使用“使用?关键字来访问我的基类方法?)
问题描述
我写了下面的代码来解释我的问题.如果我注释第 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.
这篇关于我为什么要使用“使用"?关键字来访问我的基类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我为什么要使用“使用"?关键字来访问我的基
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
