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

前端 未结 9 959
耶瑟儿~
耶瑟儿~ 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 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).

提交回复
热议问题