Jul*_*let 66 c++ oop inheritance using
我写下面的代码是为了解释我的问题.如果我注释第11行(使用关键字"using"),编译器不会编译该文件并显示以下错误:invalid conversion from 'char' to 'const char*'.它似乎没有void action(char)在Parent类中看到Son类的方法.
为什么编译器会以这种方式运行?或者我做错了什么?
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;
}
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 56
的action派生类声明隐藏action在基类声明.如果你action在一个Son对象上使用,编译器将搜索声明的方法Son,找到一个被调用的方法action,并使用它.它不会继续在基类的方法中搜索,因为它已经找到了匹配的名称.
然后该方法与调用的参数不匹配,并且您收到错误.
有关此主题的更多说明,另请参阅C++ FAQ.
需要注意的是:在这种情况下需要使用"使用"是一个红色标记,您的代码可能会让其他开发人员感到困惑(毕竟它让编译器感到困惑!).您可能应该重命名这两种方法中的一种,以便区分其他程序员.
一种可能性:
void action( const char how )
{
takeAction( &how );
}
void action( const char * how )
{
takeAction(how);
}
virtual void takeAction(const char * how) = 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37793 次 |
| 最近记录: |