LearnFrenzy
Sign in Take a free test

Static and Friend Members · Static and Friend Programs · Question 10

Matrix-vector multiplication with a friend operator in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Write Matrix2 and Vec2 classes with private data and a single friend operator*(const Matrix2&, const Vec2&) that both classes trust; rotate a vector by 90° twice.

Solution
main.cpp
#include <iostream>

class Vec2;

class Matrix2 {
    int a_, b_, c_, d_;
public:
    Matrix2(int a, int b, int c, int d) : a_(a), b_(b), c_(c), d_(d) {}
    friend Vec2 operator*(const Matrix2& m, const Vec2& v);
};

class Vec2 {
    int x_, y_;
public:
    Vec2(int x, int y) : x_(x), y_(y) {}
    friend Vec2 operator*(const Matrix2& m, const Vec2& v);
    friend std::ostream& operator<<(std::ostream& os, const Vec2& v) { return os << '(' << v.x_ << ", " << v.y_ << ')'; }
};

Vec2 operator*(const Matrix2& m, const Vec2& v) {
    return {m.a_ * v.x_ + m.b_ * v.y_, m.c_ * v.x_ + m.d_ * v.y_};
}

int main() {
    Matrix2 rot90(0, -1, 1, 0);
    Vec2 v(3, 1);
    Vec2 once = rot90 * v;
    Vec2 twice = rot90 * once;
    std::cout << v << " -> " << once << " -> " << twice << '\n';
    return 0;
}

Output Verified by compiling and running

(3, 1) -> (-1, 3) -> (-3, -1)

The multiplication needs the private entries of both classes, so both declare the same operator as a friend. Two 90° rotations equal a 180° rotation, which negates the vector.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links