用多个签名覆盖C ++虚拟方法 [英] Overriding C++ virtual methods with multiple signatures
问题描述
我有一个C ++基类,它声明了一个具有两个不同签名的虚方法。
只要覆盖派生类中的某个虚方法签名,编译器(g ++ 4.6.3和g ++ 4.7)不再能够将该方法与同一派生类中的第二个签名进行匹配。
下面的示例代码不会编译如果我只将SPECIALIZE_ONEARG定义为1.为了重新编译它,我还必须将PASSTHRU_TWOARG定义为1.使用PASSTHRU方法并不理想,因为它的效率很高,而且真正的类层次结构要深得多,而且我会
这种行为是特定于g ++还是我只是想做一些C ++不支持的东西?
#define SPECIALIZE_ONEARG(0)
#define PASSTHRU_TWOARG(0)
class base
{
public:
virtual int myMethod(char a){return 1; }
virtual int myMethod(char a,int b){return 2; }
};
class derived:public base
{
public:
#if SPECIALIZE_ONEARG
virtual int myMethod(char a){return 3; }
#endif // SPECIALIZE_ONEARG
#if PASSTHRU_TWOARG
virtual int myMethod(char a,int b){return base :: myMethod(a,b); }
#endif // PASSTHRU_TWOARG
};
int main(int argc,char * argv [])
{
派生myObj;
返回myObj.myMethod('a')* 10 + myObj.myMethod('b',0);
隐藏来自基类的定义。为了让这个定义在派生范围内可见,您需要使用base :: myMethod
。
派生类:public base
{
public:
using base :: myMethod; //< --- here
#if SPECIALIZE_ONEARG
virtual int myMethod(char a){return 3; }
#endif // SPECIALIZE_ONEARG
#if PASSTHRU_TWOARG
virtual int myMethod(char a,int b){return base :: myMethod(a,b); }
#endif // PASSTHRU_TWOARG
};
I have a C++ base class which declares a virtual method with two different signatures.
As soon as I override one of the virtual method signatures in a derived class the compiler (g++ 4.6.3 and g++ 4.7) is no longer able to match the method with the second signature in the same derived class.
The example code below will not compile if I only define SPECIALIZE_ONEARG to 1. In order to get it to compile again I also have to define PASSTHRU_TWOARG to 1. Using the "PASSTHRU" method isn't ideal because of efficiency and because the real class hierarchy is much deeper and I would prefer not to hardwire in the call to the base class.
Is this behavior specific to g++ or am I just trying to do something which isn't supported in C++?
#define SPECIALIZE_ONEARG ( 0 )
#define PASSTHRU_TWOARG ( 0 )
class base
{
public:
virtual int myMethod( char a ) { return 1; }
virtual int myMethod( char a, int b ) { return 2; }
};
class derived : public base
{
public:
#if SPECIALIZE_ONEARG
virtual int myMethod( char a ) { return 3; }
#endif // SPECIALIZE_ONEARG
#if PASSTHRU_TWOARG
virtual int myMethod( char a, int b ) { return base::myMethod( a, b ); }
#endif // PASSTHRU_TWOARG
};
int main( int argc, char* argv[])
{
derived myObj;
return myObj.myMethod( 'a' ) * 10 + myObj.myMethod( 'b', 0 );
}
Your definition is hiding the definition from the base class. In order for that definition to be visible at your derived scope, you need using base::myMethod
.
class derived : public base
{
public:
using base::myMethod; // <--- here
#if SPECIALIZE_ONEARG
virtual int myMethod( char a ) { return 3; }
#endif // SPECIALIZE_ONEARG
#if PASSTHRU_TWOARG
virtual int myMethod( char a, int b ) { return base::myMethod( a, b ); }
#endif // PASSTHRU_TWOARG
};
这篇关于用多个签名覆盖C ++虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!