How to write a C Program Friend & Operator: Vector Example in C Programming Language ?
Solution For C Program :
//C Program Friend & Operator: Vector Example.
#include <iostream>
#include <cmath>
using namespace std;
class Vector{
private:
// Data (variable part)
double x;
double y;
public:
friend void printVector(Vector v);
// Operation (function part)
//Constructive
Vector(){
x = 0;
y = 0;
}
Vector(double a, double b){
x = a;
y = b;
}
double getX(){
return x;
}
double getY(){
return y;
}
Vector operator+(Vector b){
Vector c(x+b.x, y+b.y);
return c;
}
double getLength(){
return sqrt(x*x + y*y);
}
};
void printVector(Vector v){
cout << "(" << v.x << "," << v.y << ")" << endl;
}
/*
Vector vectorAdd(Vector a, Vector b){
Vector c(a.x+b.x, a.y+b.y);
return c;
}
*/
int main(){
Vector a(3, 4), b(4, 5);
/*
a.getX();
b.getX();
*/
Vector c = a + b;//a.operator+(b);
printVector(c);
return 0;
}