#include #include #include using namespace std; template class matrix { public: int width, height; T* data; // matrix() : width(0), height(0), data(0) {} matrix(int w, int h) : width(w), height(h) { data = new T[w*h]; zero(); } void zero(){ for(int i = 0; i < width*height; i++) data[i] = 0.0; } matrix(const matrix& other) { width = other.width; height = other.height; data = new T[width*height]; // Assumes T is a basic type that doesn't require a constructor call memcpy(data, o.data, sizeof(T) * width * height); } T& at(int x, int y){ return data[x + y * width]; } matrix& operator=(matrix& o) { // If the height or width don't match, we'll adapt to the other matrix if(o.height != height || o.width != width){ height = o.height; width = o.width; delete [] data; data = new T[height*width]; } // Again, assumes memcpy(data, o.data, sizeof(T) * width * height); return *this; } matrix operator+(matrix& o) { if(o.height != height || o.width != width) throw runtime_error("Matrix size didn't match"); matrix result(width, height); for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) result.at(i, j) = at(i, j) + o.at(i, j); } return result; } ~matrix(){ delete [] data; } }; template ostream& operator<<(ostream& out, matrix& m){ for(int i = 0; i < m.height; i++) { for(int j = 0; j < m.width; j++) out << m.at(i, j) << "\t"; out << endl; } return out; } int main(){ matrix dblm(4, 4); dblm.at(1, 1) = 234.56; cout << dblm << endl; matrix extra(4, 4); extra.at(1, 1) = 2.345; matrix result(dblm + extra); cout << result; matrix copy(4, 4); copy = result; // Uses operator = matrix other_copy(result); // Uses copy constructor return 0; }