Boost数学库中有一个多项式类:Boost polynomial class。我想通过添加新函数来扩展这个类的功能,并使用继承,如下所示:
#ifndef POLY_HPP
#define POLY_HPP
#include <boost/math/tools/polynomial.hpp>
template <class T>
class Poly : public boost::math::tools::polynomial<T>{
public:
Poly(const T* data, unsigned order) : boost::math::tools::polynomial<T>(data, order){
}
};
#endif 现在我声明了这个类的两个对象,并且我想添加它们:
int a[3] = {2, 1, 3};
Poly<int> poly(a, 2);
int b[2] = {3, 1};
Poly<int> poly2(b, 1);
std::cout << (poly + poly2) << std::endl;但是编译过程中有一个错误:
main.cpp: In function ‘int main()’:
main.cpp:28:26: error: ambiguous overload for ‘operator+’ in ‘poly + poly2’
/usr/local/include/boost/math/tools/polynomial.hpp:280:22: note: candidates are: boost::math::tools::polynomial<T> boost::math::tools::operator+(const U&, const boost::math::tools::polynomial<T>&) [with U = Poly<int>, T = int]
/usr/local/include/boost/math/tools/polynomial.hpp:256:22: note: boost::math::tools::polynomial<T> boost::math::tools::operator+(const boost::math::tools::polynomial<T>&, const U&) [with T = int, U = Poly<int>]
/usr/local/include/boost/math/tools/polynomial.hpp:232:22: note: boost::math::tools::polynomial<T> boost::math::tools::operator+(const boost::math::tools::polynomial<T>&, const boost::math::tools::polynomial<T>&) [with T = int]
make[2]: Leaving为operator+定义了三个重载函数。我想它应该是:
boost::math::tools::polynomial<T> boost::math::tools::operator+(const boost::math::tools::polynomial<T>&, const boost::math::tools::polynomial<T>&)因为Poly类是从Boost多项式继承而来的,并且参数传递的是最好的,但是它不会发生。如何在没有显式定义operator+的情况下添加两个Poly类对象?
发布于 2011-07-26 22:08:14
据我所知,这是不可能的,你需要像这样的东西
template <class T>
Poly<T> operator + (const Poly<T>& a, const Poly<T>& b) {
return Poly<T>(static_cast< boost::math::tools::polynomial<T> >(a) +
static_cast< boost::math::tools::polynomial<T> >(b));
}为了消除调用的歧义(这需要在类中使用适当的从boost::math::tools::polynomial<T>到Poly<T>的转换构造函数...)
https://stackoverflow.com/questions/6831094
复制相似问题