【问题标题】:Can't find error in template class在模板类中找不到错误
【发布时间】:2018-06-28 12:03:14
【问题描述】:
template< typename T >
double GetAverage(T tArray[], int nElements)
{
    T tSum = T(); // tSum = 0
    for (int nIndex = 0; nIndex < nElements; ++nIndex)
    {
      tSum += tArray[nIndex];
    }
    // convert T to double
    return double(tSum) / nElements;
};

template <typename T>
class pair {
public:
    T a;
    T b;
    pair () {
        a=T(0);
        b=T(0);
    } ;
    pair (T a1, T b1) {
        a=a1;
        b=b1;
    };
    pair operator += (pair other_pair) {
        return pair(a+other_pair.a, b+other_pair.b);
    }

   operator double() {
       return double(a)+ double(b);
    }
};

int main(void)
{
    pair<int > p1[1];
    p1[0]=pair<int >(3,4);
    std::cout<< GetAverage <pair <int >>(p1,1) <<"\n";
}

我不明白为什么它打印的是 0 而不是 3.5。

当我从C++ -- How to overload operator+=? 复制代码时,一切正常。但我不明白我在哪里做了 一个错误

【问题讨论】:

  • 你没有“只是复制它”。您按值而不是按引用获取参数。这只是一个例子。

标签: c++ templates operator-overloading


【解决方案1】:
pair operator += (pair other_pair) {
    return pair(a+other_pair.a, b+other_pair.b);
}

应该是

pair &operator += (const pair &other_pair) {
    a += other_pair.a;
    b += other_pair.b;
    return *this;
}

您需要修改this 的成员并返回对*this 的引用,而不是一个新对象。 将other_pair 传递为const reference 而不是by value 也是一个好主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多