【问题标题】:Binary operator overloading [duplicate]二元运算符重载
【发布时间】:2017-12-16 12:14:00
【问题描述】:

我正在尝试使用重载运算符“+”创建模板多项式类。我设法使它适用于基于相同变量类型的对象(int + int),但现在我坚持让它适用于基于不同类型变量的对象(float +int)。 我想根据我要求和的多项式类型来选择我会得到什么样的结果。像这样的:

float + int -> float;
float + double -> double;
int + int -> int;
unsigned int + int -> int;

等等。

现在我有以下代码:

    template <class ScalarType>
    class Polynomial {

    public:
      Polynomial<ScalarType> operator+ (const Polynomial<ScalarType>& other) const;

}

template <class ScalarType>
Polynomial<ScalarType> Polynomial<ScalarType>::operator+ (const Polynomial<ScalarType>& other) const {
  bool firstIsMore = this->size() > other.size();
  Polynomial<ScalarType> result(firstIsMore ? *this : other);

  typename std::vector<ScalarType>::iterator resultIt = result.nc_begin();
  typename std::vector<ScalarType>::const_iterator summIterBegin = (firstIsMore ? other.begin() : this->begin());
  typename std::vector<ScalarType>::const_iterator summIterEnd = (firstIsMore ? other.end() : this->end());

  while (summIterBegin != summIterEnd) {
    *resultIt += *summIterBegin;
    resultIt++;
    summIterBegin++;
  }

  return(result);
}

这是我创建必要功能的尝试

  template <class OtherScalar>
  Polynomial<ScalarType> operator+ (const Polynomial<OtherScalar>& other) const;


template <class ScalarType>
class Polynomial {

public:

  template <class OtherScalar>
  Polynomial<ScalarType> operator+ (const Polynomial<OtherScalar>& other) const;

}

template <class ScalarType>
template <class OtherScalar>
Polynomial<ScalarType> Polynomial<ScalarType>::operator+ (const Polynomial<OtherScalar>& other) const {

  std::vector<ScalarType> summResult = this->getCoefficients();
  std::vector<OtherScalar> toSumm = other.getCoefficients();

  std::transform(summResult.begin(),
                 summResult.end(),
                 toSumm.begin(),
                 summResult.begin(),
                 [](const ScalarType& first, const OtherScalar& second){return (first + second);});

  if (summResult.size() < toSumm.size()) {
    summResult.insert(summResult.end(), toSumm.begin() + (toSumm.size() - summResult.size()), toSumm.end());
  }

  return(Polynomial(summResult));
}

但如果我使用它,我将根据二进制表达式中的第一个类型获得多项式,这不是我需要的。

最后的问题:是否可以创建基于操作数类型返回结果但不考虑其顺序的二元运算符。 (因为它适用于简单的数字类型,所以它是可能的,但我不知道如何使这项工作)

我将多项式的系数存储在std::vector&lt;ScalarType&gt; Here 是完整的类代码

【问题讨论】:

标签: c++ oop c++11 templates stl


【解决方案1】:

我想decltype() 可以帮助你。

类似

template <class OtherScalar>
Polynomial<decltype(ScalarType()+OtherScalar())> operator+
   (const Polynomial<OtherScalar>& other) const;

ps:注意:未测试

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多