我有一个名为RealAlgebraicNumber的“抽象”超类和两个名为IntervalRepresentation和NumericRepresentation的继承类。 IntervalRepresentation和NumericRepresentation都有一个复制构造函数,它们工作正常。
我像这样使用shared_ptr:
typedef std::tr1::shared_ptr<RealAlgebraicNumber> RealAlgebraicNumberPtr;
在程序的另一部分,我想使用抽象超类RealAlgeraicNumber的复制构造函数:
RealAlgebraicPoint RealAlgebraicPoint::conjoin (const RealAlgebraicNumber& N)
{
vector<RealAlgebraicNumberPtr> v (mNumbers.begin(), mNumbers.end());
v.push_back(RealAlgebraicNumberPtr(new RealAlgebraicNumber(N)));
return RealAlgebraicPoint(v);
}
我根本没有为RealAlgebraicNumber定义一个拷贝构造函数。我不知道应该做什么。编译器可以很好地使用代码,但是当我测试这样的连接时很不错:
vector<RealAlgebraicNumberPtr> v;
v.push_back(RealAlgebraicNumberPtr(new NumericRepresentation(2)));
RealAlgebraicPoint PPP (v);
PPP.print();
PPP = PPP.conjoin (NumericRepresentation(3));
PPP.print();
输出结果为:
(2)(2 null)
印刷的定义如下:
void RealAlgebraicNumberFactory::print (const RealAlgebraicNumberPtr& A)
{
IntervalRepresentationPtr irA = std::tr1::dynamic_pointer_cast<IntervalRepresentation> (A);
NumericRepresentationPtr nrA = std::tr1::dynamic_pointer_cast<NumericRepresentation> (A);
if (irA != 0)
cout << irA->Interval();
else if (nrA != 0)
cout << static_cast<numeric>(*nrA);
else
cout << "null";
}
我使用循环调用静态打印函数并将表示放在()。
之间我尝试了Cat Plus Plus的方式:RealAlgebraicNumber中的虚拟方法,
virtual std::tr1::shared_ptr<RealAlgebraicNumber> clone();
实施例如NumericRepresentation
RealAlgebraicNumberPtr NumericRepresentation::clone()
{
return RealAlgebraicNumberPtr(new NumericRepresentation(*this));
}
然后在concoin中使用它:
RealAlgebraicPoint RealAlgebraicPoint::conjoin (const RealAlgebraicNumber& N)
{
vector<RealAlgebraicNumberPtr> v (mNumbers.begin(), mNumbers.end());
v.push_back(RealAlgebraicNumberPtr(N.clone()));
return RealAlgebraicPoint(v);
}
现在编译器抱怨:
RealAlgebraicPoint.cpp: In member function 'GiNaC::RealAlgebraicPoint GiNaC::RealAlgebraicPoint::conjoin(const GiNaC::RealAlgebraicNumber&)':
RealAlgebraicPoint.cpp:66:48: error: passing 'const GiNaC::RealAlgebraicNumber' as 'this' argument of 'virtual std::tr1::shared_ptr<GiNaC::RealAlgebraicNumber> GiNaC::RealAlgebraicNumber::clone()' discards qualifiers
我不明白!怎么了?
编辑:好吧!它与const和虚拟有关。
谢谢!
勒夫
答案 0 :(得分:2)
如果您没有定义复制ctor,编译器将生成一个默认的,执行成员复制。你可能想要的是多态克隆,保留类型,并调用适当的拷贝ctor。为此,添加一个新的虚拟成员,例如virtual RealAlgebraicNumber* clone();
,并在每个子类中覆盖它以执行return new T(*this);
- 然后您的conjoin
将如下所示:
RealAlgebraicPoint RealAlgebraicPoint::conjoin (const RealAlgebraicNumber& N)
{
vector<RealAlgebraicNumberPtr> v(mNumbers.begin(), mNumbers.end());
v.push_back(RealAlgebraicNumberPtr(N.clone()));
return RealAlgebraicPoint(v);
}