ok, hazim sem cely kod, omlouvam se tem, kterym to vadi :) takhle jak to je, tak to jde zkompilovat, ale kdyz chci ten operator scitani pouzit v main, tak to zacne kricet prave cosi o tech ruznych typech. Jeste chci pretizit dalsi binarni operatory, takze ten problem je pro me dost klicovej. Jo, mam tam trochu bordel v tom, ze neco jsem nadefinoval hned v te sablone, neco az zvlast, ale na funkcnost to snad nema vliv.
#include <iostream>
#include <cstdlib>
using namespace std;
template <class Type, int N=2>
class Vector
{
Type * array;
int size, maxSize;
public:
Vector();
Vector(int n);
Vector(const Vector & v);
virtual ~Vector();
Type & operator [](int i);
friend ostream& operator<<(ostream& o, Vector& v) {
o << "(";
for (int i = 0; i < v.length(); i++) {
o << v[i];
if (i < v.length() - 1) o << ",";
}
o << ")"<< endl;
return o;
}
Vector & operator=(const Vector & v);
Vector & operator+(const Vector<Type, N>& v) {
if (v.size!=size) {
cerr << "error vector::operator+, can't add vectors of different size" << endl;
exit(1);
}
Vector<Type, N> temp;
for(int i=0;i<size;i++) temp.array[i]=array[i]+v.array[i];
return temp;
}
int length() const;
};
////////////////////////////////////
//----------DEFINICE----------//
////////////////////////////////////
template <class Type, int N>
Vector<Type, N>::Vector() {
maxSize=N;
array = new Type[maxSize];
for(int i=0;i<N;i++) array[i]=0;
size=N;
}
template <class Type, int N>
Vector<Type, N>::Vector(int n) {
maxSize=N;
if (N < 0) {
cerr << "error -- creating a Vector of negative capcity\n";
exit(1);
}
for(int i=0;i<N;i++) array[i]=n;
size=N;
}
template <class Type, int N>
Vector<Type, N>::Vector(const Vector & v) {
if (this == &v) {
cerr << "error -- cannot copy a vector to itself\n";
exit(1);
}
array = 0;
array = new Type[v.maxSize];
size = v.length( );
maxSize = v.maxSize;
for (int i = 0; i < v.length( ); i++) {
array[i] = v.array[i];
}
}
template <class Type, int N>
Vector<Type, N>::~Vector() {
delete [] array;
}
template <class Type, int N>
Type & Vector<Type, N>::operator [] (int i) {
if (i < 0 || i >= size) {
cerr << "error -- index out of range\n";
exit(1);
}
return array[i];
}
template <class Type, int N>
Vector<Type, N> & Vector<Type, N>::operator=(const Vector & rhs) {
if (this == &rhs) {
cerr << "error -- cannot assign a vector to itself\n";
exit(1);
}
delete [] array;
size = rhs.length( );
maxSize = rhs.maxSize;
array = new Type[maxSize];
for (int i = 0; i < size; i++)
array[i] = rhs.array[i];
return *this;
}
template <class Type, int N>
int Vector<Type, N>::length() const {
return size;
}
//////////////////////////////
//-----------MAIN-----------//
//////////////////////////////
int main(int argc, char *argv[])
{
Vector<double, 3> b;
b[0]=0.6;
b[1]=1.4;
b[2]=5.1;
cout << b;
Vector<int, 3> c;
c[0]=4.7;
c[1]=1.1;
c[2]=7.1;
cout << c;
//a ted bych tu chtel neco jako d=b+c;
system("PAUSE");
return EXIT_SUCCESS;
}