samedi 27 juin 2020

Operators overloading add using operator+ for a class-template

I need a function to add values ​​to v[i] using the operator+ the vector v contains the values 10,2 and 3.

#include <iostream>
#include <vector>

template<typename T>
class Measurement 
{
private:
    T val;
public:
    Measurement(T a)
        : val{ a }
    {}

    T value() const { return val; }

    Measurement<T>& operator+(const T& nr) 
    {
        //... ???
        return *this;
    }

};

int main()
{
    //create a vector with values (10,2,3)
    std::vector<Measurement<int>> v{ 10,2,3 };
    v[2] + 3 + 2; //add at v[2] value 5
    for (const auto& m : v) std::cout << m.value() << ",";
    return 0;
}

The result must be 10,2,8

Aucun commentaire:

Enregistrer un commentaire