Fun with C++

Started by TomToad, June 14, 2017, 01:48:44

Previous topic - Next topic

TomToad

Been spending the last few days trying to relearn C++.  I messed around with it many years ago (back in the 90's), many things I've forgotten and many changes to the language.

Made this handy little class which stores two numbers in a range and interpolates between them by subscripting an array with a double.
#include <iostream>

class Range
{
private:
    double m_start, m_finish;

public:
    Range(double start, double finish) : m_start(start), m_finish(finish) {}

    double operator[](const double inter)
    {
        return (m_finish-m_start)*inter+m_start;
    }
};

int main()
{
    Range range(10,20);
    for(double i = 0.0;i <= 1.0; i += 0.1)
        std::cout << range[i] << ' ';

    std::cout << std::endl;

    Range range2(100,50);
    for(double i = 0.0; i <= 1.0; i += 0.1)
        std::cout << range2[i] << ' ';

    std::cout << std::endl;
}
------------------------------------------------
8 rabbits equals 1 rabbyte.

TomToad

ok, now when you subscript range with an integer, [0] refers to the start value and [1] refers to the finish value. This way, you can get/set the values.  If range is subscripted with a double, then the return value is a linear interpolation between the two values.  I know this is probably abusing the overloading function, but it is interesting what you can do.  :)
#include <iostream>

class Range
{
private:
    double m_start, m_finish;

public:
    Range(double start, double finish) : m_start(start), m_finish(finish) {}

    double operator[](const double inter)
    {
        return (m_finish-m_start)*inter+m_start;
    }

    double& operator[](const int sub)
    {
        if (sub==0) return m_start;
        return m_finish;
    }
};

int main()
{
    Range range(10,20);
    std::cout << "start = " << range[0] << ", finish = " << range[1] << std::endl;
    for(double i = 0.0;i <= 1.0; i += 0.1)
        std::cout << range[i] << ' ';

    std::cout << std::endl;

    range[0] = 100;
    range[1] = 50;
    std::cout << "start = " << range[0] << ", finish = " << range[1] << std::endl;
    for(double i = 0.0; i <= 1.0; i += 0.1)
        std::cout << range[i] << ' ';

    std::cout << std::endl;
}
------------------------------------------------
8 rabbits equals 1 rabbyte.