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.
这篇关于我为什么要使用“使用"?关键字来访问我的基类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我为什么要使用“使用"?关键字来访问我的基
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
