具有运算符重载的模板类

时间:2016-06-11 11:02:58

标签: c++ class templates operator-overloading

以下是关于模板类

的问题
aclass<int> A{1,2};
aclass<float> B{3.0,4.0};
aclass<int> C;

int main()
{
  C=A+B;   //How to overload this operator in a simple way?
  B=A;   //And also this?
  return 0;
}

如何重载运算符来处理不同类型的模板类? (抱歉我的英语不好)

1 个答案:

答案 0 :(得分:0)

您可以在类模板中包含成员函数模板:

template <typename T>
struct aclass
{
    aclass(aclass const &) = default;
    aclass & operator=(const aclass &) = default;

    template <typename U>
    aclass(aclass<U> const & rhs) : a_(rhs.a_), b_(rhs.b_) {}

    template <typename U>
    aclass & operator=(aclass<U> const & rhs)
    {
        a_ = rhs.a_;
        b_ = rhs.b_;
        return *this;
    }

    T a_, b_;
};
相关问题