Can I create a new operator in C++ and how?

前端 未结 9 921
耶瑟儿~
耶瑟儿~ 2020-11-27 18:43

MATLAB arrays support matrix operations and element operations. For example, M*N and M.*N. This is a quite intuitive way to distinguish ‎the two di

相关标签:
9条回答
  • 2020-11-27 18:45

    It's as simple (and as difficult!) as defining a function named (in this case) operator*():

    Matrix operator*(const Matrix &m1, const Matrix &m2) ...
    

    where Matrix is a class you've defined to represent matrices.

    0 讨论(0)
  • 2020-11-27 18:47

    As other answers say, overloading operator.* is not possible.

    But I got a good solution for your question, check here.

    You can provide any methods in operator-ish form like:

    M <matrix_mul> N
    
    0 讨论(0)
  • 2020-11-27 18:50

    MATLAB arrays support matrix operations and element operations. For example, M*N and M.*N. This is a quite intuitive way to distinguish ‎the two different operations. If I want to implement similar operations in C++, how can I do that?

    Can I create a new operator, .*, too? If yes, can anyone give me some guidance?

    As for the first part you can overload most of the operators and there are some that you can not overload and the list of operators in C++ are:

    • Arithmetic

      • + (addition)
      • - (subtraction)
      • * (multiplication)
      • / (division)
      • % (modulus)
    • Bitwise

      • ^ (XOR)
      • | (OR)
      • & (AND)
      • ~ (Complement)
      • << (Shift Left, Insertion to Stream)
      • >> (Shift Right, Extraction from Stream)
    • Assignment

      • = (Assignment)
    • Relational

      • == (Equality)
      • != (Inequality)
      • > (Greater-Than)
      • < (Less-Than)
      • >= (Greater-Than Or Equal-To)
      • <= (Less-Than Or Equal-To)
    • Logical

      • ! (NOT)
      • && (AND)
      • || (OR)
    • Compound Assignment

      • += (Addition-Assignment)
      • -= (Subtraction-Assignment)
      • *= (Multiplication-Assignment)
      • /= (Division-Assignment)
      • %= (Modulus-Assignment)
      • &= (AND-Assignment)
      • |= (OR-Assignment)
      • ^= (XOR-Assignment)
      • <<= (Shift-Left Assignment)
      • >>= (Shift-Right Assignment)
    • Increment - Decrement - Both have 2 forms (prefix) and (postfix)

      • ++ (Increment)
      • -- (Decrement)
    • Subscript

      • [] (Subscript)
    • Function Call

      • () (Function Call)
    • Address, Reference, Pointer

      • operator&()
      • operator*()
      • operator->()
    • Comma

      • operator,()
    • Member Reference

      • operator->()
      • operator->*()
    • Memory Management

      • new
      • delete
      • new[]
      • delete[]
    • Conversion

      • operator "type" () const
    • NON Modifiable Operators - Operators that can not be overloaded

      • ?: (Conditional - Ternary)
      • . (Member Selection)
      • .* (Member Selection With Pointer To Member)
      • :: (Scope Resolution)
      • sizeof() (Object Size Information)
      • typeid() (Object Type Information)

    So knowing this list will help to answer your questions. Can you Create a "New Operator" in C++? No! If you want to implement similar operations in C++; how can I do that?

    You have 4 choices: Either overload an already existing operator that can be overloaded, write a function or method to do the type of calculations you want to perform, create a template type to do the work for you, or the last one which is the least common to do but you can also write macros to do them for you.

    There is a header only Math API Library that is used quite frequently with OpenGL graphics API and OpenGL's Shader Language GLSL and this library has many features that work with vectors, matrices, quaternions etc., and all the necessary functions and operations that can be done to them. Here is the link to GLM You can have a look at their documentation as well as their library implementations since it is a headers only library or API. This should give you some insight on how they constructed their Vector and Matrix objects and the operations that can be done to them.

    0 讨论(0)
  • 2020-11-27 18:51

    No, you can't overload op.*:

    [C++03 & C++11: 13.5/3]: The following operators cannot be overloaded:

    . .* :: ?:
    
    0 讨论(0)
  • 2020-11-27 18:55

    Most of the answers have already covered which operators are and are not overloadable, but none have discussed WHY some are mutable and some aren't.

    The following is a quote from Bjarne Stroustrup (the guy who wrote c++) that I found in this stackoverflow answer. Pay particular attention to the third paragraph.

    When I decided to allow overloading of operator ->, I naturally considered whether operator . could be similarly overloaded.

    At the time, I considered the following arguments conclusive: If obj is a class object then obj.m has a meaning for every member m of that object's class. We try not to make the language mutable by redefining built-in operations (though that rule is violated for = out of dire need, and for unary &).

    If we allowed overloading of . for a class X, we would be unable to access members of X by normal means; we would have to use a pointer and ->, but -> and & might also have been re-defined. I wanted an extensible language, not a mutable one.

    These arguments are weighty, but not conclusive. In particular, in 1990 Jim Adcock proposed to allow overloading of operator . exactly the way operator -> is.

    A page on his website adds a little more:

    Can I define my own operators?

    Sorry, no. The possibility has been considered several times, but each time I/we decided that the likely problems outweighed the likely benefits.

    It's not a language-technical problem. Even when I first considerd it in 1983, I knew how it could be implemented. However, my experience has been that when we go beyond the most trivial examples people seem to have subtlely different opinions of "the obvious" meaning of uses of an operator. A classical example is a ** b ** c. Assume that ** has been made to mean exponentiation. Now should a ** b ** c mean (a ** b) ** c or a ** (b ** c)? I thought the answer was obvious and my friends agreed - and then we found that we didn't agree on which resolution was the obvious one. My conjecture is that such problems would lead to subtle bugs.

    So, while most operators can be overloaded, it was never intended for people to create arbitrary operators in c++.

    0 讨论(0)
  • 2020-11-27 19:00

    You cannot overload .* (see Lightness' answer for standard text), but, interestingly enough, you can overload ->* (similar to how you can overload -> but not .). If that's sufficient for differentiation, then have at it:

    struct Int {
        int i;
    
        Int operator*(Int rhs) const { return Int{i * rhs.i}; }
        Int operator->*(Int rhs) const { return Int{i + rhs.i}; }
    
        friend std::ostream& operator<<(std::ostream& os, Int rhs) {
            return os << "Int(" << rhs.i << ')';
        }
    };
    
    int main() {
        Int five{5};
        Int six{6};
    
        std::cout << (five * six) << ", " << (five ->* six) << '\n';
    }
    

    That'll print Int(30), Int(11).

    0 讨论(0)
提交回复
热议问题