Personal tools
Document Actions


by aullmj — last modified 2009-01-26 18:00

structures demo code

Click here to get the file

Size 1 kB - File type text/x-c++src

File contents

//companion code to lecture on classes
//Mark Aull, 2008

#include <math.h>
#include <iostream>
using namespace std;

struct vec2{
	double x,y;
	vec2(double X=0,double Y=0):x(X),y(Y){}
	//implicit copy constructor and destructor
	double length(void){return sqrt(x*x+y*y);}
	friend ostream& operator<< (ostream& str,vec2 v){str<< '('<<v.x<<','<<v.y<<')'; return str;}
	friend vec2 operator+(vec2 lhs,vec2 rhs);
	friend vec2 operator-(vec2 v);
	friend vec2 operator-(vec2 lhs,vec2 rhs){return lhs+(-rhs);}

void main(void)

	vec2 a;
	vec2 b(23,5);
	//vec2 a,b(23,5);
	a.x=5; a.y=15;
	cout << a.length()<<endl;
	cout << '<'<< b.x<<','<<b.y<<'>'<<endl;
	cout << a<<'\t'<<b<<endl;
	cout <<a+b<<endl;
	cout <<-a<<endl;

vec2 operator+(vec2 lhs,vec2 rhs)
	cout << "using + operator"<<endl;
	vec2 sum(rhs.x+lhs.x,lhs.y+rhs.y);
	return sum;

vec2 operator-(vec2 v)
	cout << "using negative operator"<<endl;
	vec2 res(-v.x,-v.y); return res;
Related content