首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >operator+的二义性重载

operator+的二义性重载
EN

Stack Overflow用户
提问于 2011-07-26 21:54:18
回答 1查看 834关注 0票数 2

Boost数学库中有一个多项式类:Boost polynomial class。我想通过添加新函数来扩展这个类的功能,并使用继承,如下所示:

代码语言:javascript
复制
#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 

现在我声明了这个类的两个对象,并且我想添加它们:

代码语言:javascript
复制
    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;

但是编译过程中有一个错误:

代码语言:javascript
复制
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+定义了三个重载函数。我想它应该是:

代码语言:javascript
复制
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类对象?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-07-26 22:08:14

据我所知,这是不可能的,你需要像这样的东西

代码语言:javascript
复制
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>的转换构造函数...)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6831094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档