How to make a wacky math calculator? (Preferably in c++ but others are ok too.)

百般思念 提交于 2019-12-05 20:16:59

I said in my comment that this would imply macros in C++; if what you want is not much more complicated than what you show, it should do the trick. Defining operators as macros should work for simple find/replace cases, but it may not be well suited for complex expressions and certain symbols.

Off my head, I think what you want is feasible in Haskell by using infix functions as operators, but it may not be straight-forward for a beginner. Take a look at Lyah and search for infixr. You need a basic knowledge of Haskell though.

Edit with Zeta example, you can run it in ghci:

(<+>) = (-) -- operator definition
(<*>) = (/)

answer = 42
answer <+> 12 -- prints 30
answer <*> 7 -- prints 6.0

You can wrap the types into a class, then overload the operators. I came up with a minimal example for "wacky" addition (+ becomes -). But if you want to use PODs you have to use the preprocessor, there is no other way.

#include <iostream>
using namespace std;

template<typename T>
class wacky
{
    T val_;
public:
    wacky(T val = {}): val_(val){};

    // let's define a conversion operator
    template<typename S>
    operator S (){return val_;}

    // we don't need asignment operator and copy ctors

    // stream operators
    friend ostream& operator<<(ostream& os, const wacky& rhs)
    {
        return os << rhs.val_;
    }

    // the += operator
    wacky& operator+=(const wacky& rhs)
    {
        val_ -= rhs.val_; // wacky!
        return *this;
    }

    // and the wacky operator+
    friend wacky operator+(wacky lhs, const wacky& rhs)
    {
        return lhs+=rhs;
    }
};

int main()
{
    wacky<int> a,b;
    a = 10;
    b = 15;

    // a and b behave now like PODs
    // implicit conversions work etc
    double wacky_sum = a + b; 
    cout << wacky_sum << endl; // -5
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!