2x2 ํ๋ ฌ์ ๋ง์ /๊ณฑ์ ์ ์ํ๊ณผ ํ๋ ฌ ์ถ๋ ฅ์ ํ๋ ๊ฐ๋จํ ํ๋ก๊ทธ๋จ์ด๋ค. ์ ๋ ฅ ๋ฃ๊ธฐ ๊ท์ฐฎ์์ ๊ทธ๋ฅ ์์์ ๊ฐ ์ค์ ํด๋จ๋ค.
#include <iostream>
#include <string>
using namespace std;
struct Point {
int x, y;
};
class Matrix2x2 {
public:
Point row1;
Point row2;
Matrix2x2(Point r1, Point r2) {
row1 = r1;
row2 = r2;
}
Matrix2x2 operator+(const Matrix2x2& other) const {
return Matrix2x2(
{ row1.x + other.row1.x, row1.y + other.row1.y },
{ row2.x + other.row2.x, row2.y + other.row2.y }
);
}
Matrix2x2 operator*(const Matrix2x2& other) const {
return Matrix2x2(
{
row1.x * other.row1.x + row1.y * other.row2.x,
row1.x * other.row1.y + row1.y * other.row2.y
},
{
row2.x * other.row1.x + row2.y * other.row2.x,
row2.x * other.row1.y + row2.y * other.row2.y
}
);
}
friend ostream& operator<<(ostream& os, const Matrix2x2& m) {
os << "({" << m.row1.x << "," << m.row1.y << "}," <<"{" << m.row2.x << "," << m.row2.y << "})";
return os;
}
};
int main(void) {
Matrix2x2 m1({ 1,2 }, { 3,4 });
Matrix2x2 m2({ 5,6 }, { 7,8 });
Matrix2x2 result = m1 + m2;
Matrix2x2 result2 = m1 * m2;
cout << result << endl;
cout << result2;
return 0;
}์ฐ์ ์ฐ์ฐ์ ์ค๋ฒ๋ก๋ฉ์ด ๋ฌด์์ธ์ง๋ถํฐ ์์๋ณด์. '+' '*' '<<' ์ด ๊ธฐํธ๋ค ๋ณด๋ฉด ์๋ ๊ฑ ๋ง์
๊ณฑ์
์ถ๋ ฅ์ด์๋ ์ฅ๋? ์ด๋ฐ ์๊ฐ์ด ๋จผ์ ๋ค๊ฒ ๋๋ค. ํ์ง๋ง ํน์ดํ ํํ์ ์ฐ์ฐ์ ํ๋ค๊ณ ์๊ฐํด๋ณด์. 2+2๋ฅผ ํ๋ฉด int+int๋๊น ์์ฐ์ค๋ฝ๊ฒ 4๊ฐ ์ถ๋ ฅ๋๋ค. ๊ทธ๋ฌ๋ 2x2 ํ๋ ฌ๊ณผ ๊ฐ์ด { 1,2 }, { 3,4 } + { 5,6 }, { 7,8 } ๋ฃ์ผ๋ฉด ์ฌ๋์ ๋จธ๋ฆฌ ๊ตด๋ ค์ ๊ณ์ฐ ๊ฐ๋ฅํ๋ฐ ์ปดํจํฐ๋ ์ด๊ฒ int์ธ์ง char์ธ์ง ํ๋จ์ด ์๋๋๋ฐ ์ด์ผํด์ ์์ ํด๋ฒ๋ฆฐ๋ค.
๊ทธ๋ ๊ธฐ์ ์ฐ์ฐ์ ์ค๋ฒ๋ก๋ฉ์ ์ ๊ธฐ๋ณธ ์ฐ์ฐ์๋ฅผ ๋ด ์
๋ง๋๋ก ๋ฐ๊พธ๋ ๊ฒ์ด๋ค. ์ผ๋ฐ์ ์ธ ์ํฉ์์๋ ๊ธฐ๋ณธ ์ฐ์ฐ์์ฒ๋ผ ์๋ํ์ง๋ง, 'ํน์ ํ ์กฐ๊ฑด'์ด ๋ง์กฑ๋ ๋, ๋ด๊ฐ ๋ง๋ ์ปค์คํ
์ฐ์ฐ์๊ฐ ์คํ๋๋ค. ์ ์ฝ๋์์ ์ฌ์ฉ๋ '+' ์ฐ์ฐ์ ์ค๋ฒ๋ก๋ฉ์ ๋ณด๋๋ก ํ์
Matrix2x2 operator+(const Matrix2x2& other) const {
return Matrix2x2(
{ row1.x + other.row1.x, row1.y + other.row1.y },
{ row2.x + other.row2.x, row2.y + other.row2.y }
);
}operator '+'๋ ๋ด๊ฐ ๊ตฌ์กฐ์ฒด์ ํด๋์ค๋ฅผ ํตํด ๋ฏธ๋ฆฌ ์ค์ ํด๋ ํํ์ธ const Matrix2x2์ ๋ค์ ๋ค๋ฅธ ๊ฐ(other)์ด ํจ๊ป ์ฌ ๋ ์คํ๋๋ค. ์ฌ๊ธฐ์ other์ ํํ๋ ๋ณด๊ฒ๋๋ฉด other.row1.x, other.row2.y๋ฑ 2x2 ํ๋ ฌ์ด์ด์ผ ์คํ๋๋ค. ๋ ์ค ํ๋๋ผ๋ ํํ๋ฅผ ๋ง์กฑํ์ง ์์ผ๋ฉด ์ด ์ฐ์ฐ์ ์คํ๋์ง ์๋๋ค.
friend ostream& operator<<(ostream& os, const Matrix2x2& m) {
os << "({" << m.row1.x << "," << m.row1.y << "}," <<"{" << m.row2.x << "," << m.row2.y << "})";
return os;
}์ฌ๊ธฐ์๋ friend ๋ฅผ ์ธ ํ์ ์์ง๋ง ๊ตณ์ด๊ตณ์ด ์จ๋ดค๋ค.
์ถ๋ ฅ์ ๋ด๋นํ๋ '<<'์ ์ค๋ฒ๋ก๋ฉํ๋ ์ญํ ์ธ ๊ฑด ์๊ฒ ๋ค. ๊ทผ๋ฐ friend๋ ์ ์ฐ๋ ๊ฑธ๊น? ์ด๊ฑด public/private์ ๋ ์ฌ๋ฆฌ๋ฉด ๋๋ค. ํ์ฌ operator '<<'ํจ์์ ์์น๋ class ๋ด๋ถ์ด์ง๋ง, ๋ณธ์ง์ ์ผ๋ก๋ ์ธ๋ถ ํจ์์ด๋ค. ์ผ๋จ operator์ด ํด๋์ค์ ๋ฉค๋ฒ๊ฐ ์๋๋ฉฐ, this ํฌ์ธํฐ๋ ์ฌ์ฉํ์ง ์๊ณ ์๋ค. ๊ทธ๋์ ๋ง์ฝ row1, row2์ ๊ฐ์ด private(ํ์ฌ๋ public์ด์ง๋ง)์ผ๋ก ์ค์ ๋๋ฉด ์ ๊ทผ์ ๋ชปํ๋ ๋ถ์์ฌ๊ฐ ์๊ธธ ์๋ ์๋ค. ์ด๊ฑธ ๋ฐฉ์งํด์ฃผ๋๊ฒ friend์ด๋ค. ์ธ๋ถ ํจ์์๊ฒ private ๋ฉค๋ฒ ์ ๊ทผ ๊ถํ์ ์ฃผ๋ ๊ฒ์ด๋ค. ๋ค๋ง ์บก์ํ๋ฅผ ๋ถ๋ถ์ ์ผ๋ก ๊นจ๋ ํ์์ด๊ธฐ์ ์๊ฐ ๋ง์ด ํด๋ณด๊ณ ์จ์ผ ํ๋ค...