超载运营商“+”添加两个数组在C ++中 [英] Overload operator '+' to add two arrays in C++

查看:275
本文介绍了超载运营商“+”添加两个数组在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过写增加两个数组:

I want to add two arrays by simply writing:

int a[4] = {1,2,3,4};
int b[4] = {2,1,3,1};
int sum[4] = a + b;

我写了这个功能,但我得到了一个错误

I wrote this function but I got an error

int* operator+(const uint32& other) const{
    uint32 sum[n];
    for(int i=0; i<n; i++){
        sum[i] = (*this[i]) + other[i];
    }
    return sum;
}

你能不能帮我在这?先谢谢了。

Could you help me on this? Thanks in advance.

推荐答案

这是可能是错误的,但它似乎工作(C ++ 11):

This is probably wrong, but it appears to work (C++11):

#include <iostream>
#include <array>

using namespace std;

template <class T>
T operator+(const T& a1, const T& a2)
{
  T a;
  for (typename T::size_type i = 0; i < a1.size(); i++)
    a[i] = a1[i] + a2[i];
  return a;
}

int main()
{
  array<int,5> a1 = { 1, 2, 3, 4, 5 };
  array<int,5> a2 = { 2, 3, 4, 5, 6 };
  array<int,5> a3 = a1 + a2;

  for (int i = 0; i < 5; i++)
    cout << a1[i] << '+' << a2[i] << '=' << a3[i] << ' ';

  cout << endl;
  return 0;
}

输出( ideone ):

1+2=3 2+3=5 3+4=7 4+5=9 5+6=11 

这篇关于超载运营商“+”添加两个数组在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆