覆盖纯虚函数的参数数 [英] Override number of parameters of pure virtual functions
本文介绍了覆盖纯虚函数的参数数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已实现以下界面:
template< typename T&
类变量
{
public:
变量(T v):m_value(v){}
virtual void Callback()= 0;
private:
T m_value;
};
一个合适的派生类将被定义如下:
class Derived:public Variable< int>
{
public:
Derived(int v):Variable< int> (v){}
void Callback(){}
}但是,我想导出 Callback $ c $ c>接受不同的参数(例如: void Callback(int a,int b))
。
有办法吗?解决方案这是我跑了很多次的问题。 / p>
这是不可能的,并且有很好的理由,但是有办法实现基本相同的事情。我现在使用:
struct Base
{
virtual void execute()
virtual〜Base {}
};
class Derived:public Base
{
public:
Derived(int a,int b):mA(a),mB(b),mR ){}
int getResult()const {return mR; }
virtual void execute(){mR = mA + mB; }
private:
int mA,mB,mR;
};
在操作中:
int main(int argc,char * argv [])
{
std :: unique_ptr< Base> derived(new Derived(1,2));
derived-> execute();
return 0;
} // main
I have implemented the following interface:
template <typename T>
class Variable
{
public:
Variable (T v) : m_value (v) {}
virtual void Callback () = 0;
private:
T m_value;
};
A proper derived class would be defined like this:
class Derived : public Variable<int>
{
public:
Derived (int v) : Variable<int> (v) {}
void Callback () {}
};
However, I would like to derive classes where Callback
accepts different parameters (eg: void Callback (int a, int b))
.
Is there a way to do it?
解决方案 This is a problem I ran in a number of times.
This is impossible, and for good reasons, but there are ways to achieve essentially the same thing. Personally, I now use:
struct Base
{
virtual void execute() = 0;
virtual ~Base {}
};
class Derived: public Base
{
public:
Derived(int a, int b): mA(a), mB(b), mR(0) {}
int getResult() const { return mR; }
virtual void execute() { mR = mA + mB; }
private:
int mA, mB, mR;
};
In action:
int main(int argc, char* argv[])
{
std::unique_ptr<Base> derived(new Derived(1,2));
derived->execute();
return 0;
} // main
这篇关于覆盖纯虚函数的参数数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文