gpt4 book ai didi

c++ - operator+ 的模糊重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:58:06 25 4
gpt4 key购买 nike

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 类对象?

最佳答案

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

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> 的适当转换构造函数...)

关于c++ - operator+ 的模糊重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6831094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com