Berikut penggunaan Class dan operator overloading untuk perhitungan vector 2 dimensi dengan bahasa pemrograman C++.
mengenai apa dan bagaimana teori vector, silakan liat di sini
Vector yang dimksud adalah vector 2 dimensi yang mempunyai komponen bilangan real dan imaginer yaitu: misal vector a = 6i + 8j dan vector b = 2i + 3j. Untuk vector 3 dimensi, akan mempunyai tambahan komponen k.
:::berikut programnya:::
#include<string>
#include<complex>
#include<iostream>
// forward declaration
template <typename T>
class Vector;
template <typename T> std::ostream& operator<<(std::ostream&, const Vector<T>&);
template <typename T>
class Vector
{
private:
std::complex<T> mycomplex;
public:
Vector() {}
Vector(T i_component, T j_component) : mycomplex(i_component, j_component) {}
// member operators
Vector& operator+=(const Vector& rhs)
{
mycomplex+=rhs.mycomplex;
return *this;
}
Vector& operator-=(const Vector& rhs)
{
mycomplex-=rhs.mycomplex;
return *this;
}
Vector& operator*=(const Vector& rhs)
{
mycomplex*=rhs.mycomplex;
return *this;
}
friend std::ostream& operator<< <T>(std::ostream&, const Vector<T>&);
};
template <typename T>
const Vector<T> operator+(const Vector<T>& lhs, const Vector<T>& rhs)
{
return Vector<T>(lhs)+=rhs;
}
template <typename T>
const Vector<T> operator-(const Vector<T>& lhs, const Vector<T>& rhs)
{
return Vector<T>(lhs)-=rhs;
}
template <typename T>
const Vector<T> operator*(const Vector<T>& lhs, const Vector<T>& rhs)
{
return Vector<T>(lhs)*=rhs;
}
template <typename T>
std::ostream& operator<<(std::ostream& ostr, const Vector<T>& vect)
{
ostr << "i component : " << vect.mycomplex.real() << "\n";
ostr << "j component : " << vect.mycomplex.imag() << "\n";
return ostr;
}
int main()
{
Vector<double> x_vector(1, 10);
Vector<double> y_vector(2, 20);
Vector<double> z_vector(3, 30);
std::cout << "vector x : \n" << x_vector;
std::cout << "vector y : \n" << y_vector;
std::cout << "vector z : \n" << z_vector;
std::cout << "Hasil penjumlah vector xyz : \n" << (x_vector+y_vector+z_vector);
std::cout << "Hasil pengurangan vector xyz : \n" << (x_vector-y_vector-z_vector);
std::cout << "Hasil perkalian vector xyz : \n" << (x_vector*y_vector*z_vector);
return 0;
}
No comments:
Post a Comment