Operator Overloading in a 3D Vector Class in C++
C++
#include<iostream> using namespace std; class vector { float x; float y; float z; //data members public: vector(){ } //default constructor vector(float x,float y,float z) //parameterized constructor { this->x = x; this->y = y; this->z = z; } void display(); //member functions declaration void operator-(); //- operator overloading declaration void operator++(); //++ operator overloading declaration void operator--(); //-- operator overloading declaration }; void vector::display() //member function definition { cout<<"Vector : "<<x<<"i + "<<y<<"j + "<<z<<"k"<<endl; } void vector::operator-() //- operator overloading definition { x = -x; y = -y; z = -z; } void vector::operator++() //++ operator overloading definition { ++x; ++y; ++z; } void vector::operator--() //-- operator overloading definition { --x; --y; --z; } int main() { float a,b,c; cout<<"Enter three values : "; cin>>a>>b>>c; vector v1(a,b,c); //object created and parameterized constructor invoked v1.display(); //member function calling cout<<"-v1 : "<<endl; -v1; //operator- function calling v1.display(); cout<<"++v1 : "<<endl; ++v1; //operator++ function calling v1.display(); cout<<"--v1 : "<<endl; --v1; //operator-- function calling v1.display(); return 0; }
Enter three values : 3 4 -5
Vector : 3i + 4j + -5k
-v1 :
Vector : -3i + -4j + 5k
++v1 :
Vector : -2i + -3j + 6k
--v1 :
Vector : -3i + -4j + 5k
Learn More...
- Counting Characters in a String in C++
- Explaining the getline Function in C++
- Data Hiding in C++
- Efficient Array Sorting in C++: Static Overloaded Functions for Floats and Integers
- Programm to demonstrate constructor with default arguments
- Understanding Function Call by Value in C++
- Exploring Virtual Functions with Default Arguments in C++
- Multiple Inheritance in C++
- Binay + Operator in C++
- Exploring Class-to-Basic Type Conversion with a Product Example in C++
- Creating a Diamond Pattern in the CPP Program
- Write a CPP program to perform arithmetic operations using an inline function.
- C++ Complex Numbers Addition
- Write a program to generate the following pattern