我继承了两个类TFoamIntegrand和IBaseFunctionMultiDim,它们都是抽象类。我遇到的问题是我希望能够使用克隆成员函数,对于IBaseFunctionMultiDim来说,它是一个没有参数的纯虚函数,对于TFoamIntegrand,它不是TFoamIntegrand中的纯虚函数,而是有一个参数(带有默认值)。
class TObject {
public:
virtual TObject *Clone(const char *newname="") const;
...
};
class TFoamIntegrand : public TObject {
public:
virtual Double_t Density(Int_t ndim, Double_t *) = 0;
...
};
class IBaseFunctionMultiDim {
public:
/**
Clone a function.
Each derived class must implement his version of the Clone method
*/
virtual IBaseFunctionMultiDim * Clone() const = 0;
...
}
我可以编译的唯一方法是:
class InSANEDiffXSec : public TFoamIntegrand, public ROOT::Math::IBaseFunctionMultiDim {
public:
virtual ROOT::Math::IBaseFunctionMultiDim* Clone() const ;
...
}
当然,这会产生关于使用参数隐藏Clone的警告。我尝试了以下但是我得到了协变返回类型错误。
virtual ROOT::Math::IBaseFunctionMultiDim* Clone(const char * newname = "") const ;
virtual InSANEDiffXSec* Clone(const char * newname = "") const ;
根据我对协变返回类型的理解,我认为上面的最后一个版本是正确的。我在这里错过了什么?
提前致谢!
编辑:这是一个完整的例子:
class A {
public:
virtual A* Clone(const char * name="") { return( new A());}
};
class B {
public:
virtual B* Clone() = 0;
};
class C : public A {
public:
virtual double Density(int ndim, double *) = 0;
};
class D : public C, public B {
public:
virtual double Density(int ndim, double *x) {
return 0.0;
}
//virtual D* Clone(const char * name="") { return( new D());}
virtual B* Clone() { return( new D());}
};
它编译。更改为注释行给出:
test.h: In member function ‘virtual D* D::Clone(const char*)’:
test.h:24:62: error: cannot allocate an object of abstract type ‘D’
virtual D* Clone(const char * name="") { return( new D());}
^
test.h:19:7: note: because the following virtual functions are pure within ‘D’:
class D : public C, public B {
^
test.h:11:17: note: virtual B* B::Clone()
virtual B* Clone() = 0;
^
test.cxx: In function ‘int main()’:
test.cxx:7:18: error: cannot allocate an object of abstract type ‘D’
D * d = new D();
^
In file included from test.cxx:2:0:
test.h:19:7: note: since type ‘D’ has pure virtual functions
class D : public C, public B {
答案 0 :(得分:1)
编译:
class TObject {
public:
virtual TObject *Clone(const char *newname="") const = 0;
};
class IBaseFunctionMultiDim {
public:
virtual IBaseFunctionMultiDim * Clone() const = 0;
};
class InSANEDiffXSec :
public TObject,
public IBaseFunctionMultiDim
{
public:
virtual InSANEDiffXSec* Clone(const char* newname) const
{
return nullptr;
}
virtual InSANEDiffXSec* Clone() const
{
return Clone(nullptr);
}
};
但我确实删除了代码中似乎没有相关性的内容。