0

I am literally rookie to C++ and I'm trying to learn it in a professional way. I got familiar with the basic of defining operators in c++, but I think there are some restrictions, like you can only define operators with defined symbols. That is to say, for example, if I want to define vectorized multiply (like what is in MATLAB), it couldn't be possible. Does anyone know a way to define such operators?

A*B = returns a new matrix with new dimension compromised A and B A.*B = returns a new matrix, which all of its members are result of multiplication of A(i,j)*B(i,j)

matt sh
  • 1
  • 2
  • 1
    You can override `operator*` (so you can do `A*B`) but not `operator.*` (so cannot do `A.*B`). See [here](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) for more details on how this works in C++ – Cory Kramer May 11 '20 at 14:28
  • You can just overload operators listed here https://en.cppreference.com/w/cpp/language/operators You can't create new operators. _.* (member access through pointer to member)... cannot be overloaded._ – Thomas Sablik May 11 '20 at 14:31
  • See here for the list of operators you can overide: https://en.cppreference.com/w/cpp/language/operators – Jean-Marc Volle May 11 '20 at 14:31
  • This should be of use: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – eerorika May 11 '20 at 14:40
  • For interest of academic understanding of C++, you can make your own customer [infix operators](https://stackoverflow.com/questions/36356668/user-defined-infix-operators) ... but as Sean commented, "Please please please please don't ever do something like this in production code". – Eljay May 11 '20 at 16:31

1 Answers1

0

In general, you can make a custom operator using a struct:

struct operation {
    T operator () (T const &a, T const &b) {
        //code
    }
};

Where T is a data type.

For your case, the operator would look something like this:

struct matrix_multiplication {
    vector <vector<int>> operator () (vector <vector<int>> const &a, vector <vector<int>> const &b) {
        //insert multiplication operation here
    }
};
Littm
  • 4,923
  • 4
  • 30
  • 38