U E D R , A S I H C RSS

cpp스터디인데이름을못짓겠어요/8월11일

8월 11일


  • 연산자 오버로딩과 생성자, 소멸자, 복사 생성자에 대해 복습하고, 실습을 하였습니다.
  • 역시 실습을 하니까 오래 걸리네요

  • 벡터 클래스를 만들고
    • 덧셈과 뺄셈 (오버로딩 +, -)
    • 내적과 외적 (오버로딩 *. /)
    • 사잇각, 길이 구하기 등을 구현했습니다. (오버로딩 %)


#include<iostream>
#define _USE_MATH_DEFINES
#include<cmath>
class Vector {
	double x;
	double y;

public :

	Vector() {
		this->x = 0.0;
		this->y = 0.0;
	}

	Vector(double x, double y) {
		this->x = x;
		this->y = y;
	}


	double operator*(Vector& v2) {
		return ((this->x * v2.x) + (this->y * v2.y));
	}

	Vector operator+(Vector& v2) {
		Vector returnVector;

		returnVector.x = this->x + v2.x;
		returnVector.y = this->y + v2.y;

		return returnVector;
	}

	Vector operator-(Vector& v2) {
		Vector returnVector;

		returnVector.x = this->x - v2.x;
		returnVector.y = this->y - v2.y;

		return returnVector;
	}

	double length() {
		return sqrt(this->x * this->x + this->y * this->y);
	}


	double operator%(Vector& v2) {
		return acos( (*this * v2) / ( abs( this->length() ) * abs( v2.length() ) ) );
	}


	double operator/(Vector& v2) {
		return (this->length() * v2.length()) * sin(*this % v2);
	}
	

	void operator+=(Vector& v2) {
		Vector temp;
		temp.x = this->x + v2.x;
		temp.y = this->y + v2.y;
		this->x = temp.x;
		this->y = temp.y;
	}

	void operator-=(Vector& v2) {
		Vector temp;
		temp.x = this->x - v2.x;
		temp.y = this->y - v2.y;
		this->x = temp.x;
		this->y = temp.y;
	}

	double getX() {
		return this->x;
	}

	double getY() {
		return this->y;
	}

};

#include"operatorOverloading.cpp"

#define PI 3.1415923
using namespace std;
#ifndef __OVERLOAD__
#include <iostream>
#endif


int main() {

	Vector v1(3, 3);
	Vector v2(3, 0);

	cout << "Vector 1 : " << "(" << v1.getX() << ", " << v1.getY() << ")" << endl;
	cout << "Vector 2 : " << "(" << v2.getX() << ", " << v2.getY() << ")" << endl;

	Vector v3;

	cout << "Vector 1's length : " << v1.length() << endl;
	cout << "Vector 2's length : " << v2.length() << endl;

	v3 = v1 + v2;
	cout << "덧셈 : " << "(" << v3.getX() << ", " << v3.getY() << ")" << endl;

	v3 = v1 - v2;
	cout << "뺄셈 : " << "(" << v3.getX() << ", " << v3.getY() << ")" << endl;


	cout << "각도 : " <<  (v1 % v2) * 180 / PI << endl;
	cout << "외적 : " << v1 / v2 << endl;
	cout << "내적 : " << v1 * v2 << endl;
	
	v1 += v2;
	cout << "+= 결과 : " << endl;
	cout << "Vector 1 : " << "(" << v1.getX() << ", " << v1.getY() << ")" << endl;

	v1 -= v2;
	cout << "-= 결과 : " << endl;
	cout << "Vector 1 : " << "(" << v1.getX() << ", " << v1.getY() << ")" << endl;
	return 0;
}


  • 기타
    • cmath의 define 된 상수들을 사용하려면 _USE_MATH_DEFINES를 cmath의 include 전에 define 해주어야 함.
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:31:38
Processing time 0.0112 sec