我知道很多语言,C ++,Python等都支持运算符重载,我们可以重新定义像+这样的标准运算符。但是,如果我们需要添加新的运算符?
答案 0 :(得分:0)
Neither C++ nor Python (C++, Python) support the overloading of "new" operators (although C++ does support overloading the new
operator). Overloading operators is just syntactic sugar though - you can always just define a member function, name it something that explains its behaviour better than a single character operator could, and call it instead.
There do exist languages where this is possible: for example Haskell, a beautiful language that does allow you to define your own operators, by using symbols for the name and surrounding them with parentheses, eg:
(!!!) :: [a] -> Integer -> a
(x:xl) !!! 0 = x
(_:xl) !!! n = xl !!! (n-1)
_ !!! _ = error "Index out of bounds"
(note this is just a redefinition of the standard !!
function, I'm unimaginative...)
答案 1 :(得分:-1)
I don't think there is any language with the feature. But you can always create your own interpreter or something similar in order to process your custom code and transform it into code of the desired language. As the simplest variant, you can write a tool(or even extension for IDE), which will find something like
return_type operator$(typename arg1, typename arg2);
and insert something like
return_type reloaded_operator_dollar(typename arg1, typename arg2);
in its place. The same goes for transforming
auto result = arg1 $ arg2;
into
auto result = reloaded_operator_dollar(arg1, arg2);
upd: It seems, there are such feature in FORTH and Haskell. Thanks to Neil Butterworth for the information.