C ++运算符重载将3个向量加在一起 [英] C++ operator overloading adding 3 vectors together

查看:125
本文介绍了C ++运算符重载将3个向量加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在这是我将3个乘积类型的向量加在一起的方法:

For now this is how I add 3 vectors of type Product together:

    vector1.insert(std::end(vector1), std::begin(vector2), std::end(vector2));
    vector1.insert(std::end(vector1), std::begin(vector3), std::end(vector3));

如何使用运算符重载(假设+和=运算符重载)来简化代码?产品具有以下属性:

How do I use operator overloading (I assume overloading the + and = operators) to simplify my code? Product has the following properties:

private:
    std::string url;
    double cost;
    std::string name;
    std::string site;

推荐答案

操作重载只是普通的自由函数或成员函数.

Operating overloading is just a normal free function, or member function.

大多数情况下,它们没有什么特别的. (大部分"指的是运算符的优先级,并对operator*取消引用或operator,之类的注意事项.)

There's nothing special about them, mostly. (The "mostly" referring to operator precedence and some caveats for things like operator* dereferencing or operator,.)

以下是使用operator+=append的示例,它们显示了相同的功能:

Here is an example using operator+= and append showing they do the same thing:

#include <iostream>
#include <vector>

using std::begin;
using std::cout;
using std::end;
using std::endl;
using std::ostream;
using std::vector;

struct Product
{
  static int count;
  int i;
  Product() : i{++count} {}
};

static ostream& operator<<(ostream& o, Product const& p)
{
  o << p.i;
  return o;
}

int Product::count = 100;

static void append(vector<Product>& v, vector<Product> const& v2)
{
  v.insert(end(v), begin(v2), end(v2));
}

static vector<Product>& operator+=(vector<Product>& v, vector<Product> const& v2)
{
  v.insert(end(v), begin(v2), end(v2));
  return v;
}

int main()
{
  auto product1 = vector<Product>{};
  product1.push_back(Product{});
  product1.push_back(Product{});
  product1.push_back(Product{});
  product1.push_back(Product{});

  auto product2 = vector<Product>{};
  product2.push_back(Product{});
  product2.push_back(Product{});
  product2.push_back(Product{});
  product2.push_back(Product{});

  auto product3 = vector<Product>{};
  product3.push_back(Product{});
  product3.push_back(Product{});
  product3.push_back(Product{});
  product3.push_back(Product{});

  append(product1, product2);
  product1 += product3;

  char const* sep = "";
  for (auto const& p : product1)
  {
    cout << sep << p;
    sep = " ";
  }
  cout << endl;
}

这篇关于C ++运算符重载将3个向量加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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