2011-07-26 88 views
2

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類對象,而沒有顯式的operator +新定義?

+0

'polynomial '有一個虛擬析構函數嗎?我不這麼認爲,因此公開繼承它是非常危險的 –

回答

2

這是不可能的,因爲據我所知,你需要像

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>在類...)