cpp:vector_overloading
This is an old revision of the document!
Παράδειγμα υπερφόρτωσης τελεστών
Ας υποθέσουμε ότι έχουμε την παρακάτω κλάση Vector η οποία υλοποιεί ένα μονοδιάστατο πίνακα από ακεραίους.
- Vector.hpp
#include <iostream> #include <cstdlib> using namespace std; #ifndef _VECTOR_HPP_ #define _VECTOR_HPP_ class Vector { int *array; int size; public: Vector(int length=0); Vector(const Vector &v); Vector(const Vector *v); ~Vector(); int length() const;// return Vector's length. int &valueAt(int pos) const; // return a reference to element at position pos int find(int a) const; // check if a exists in Vector. Return it position >0 or -1 // if not element not found void print() const; // print vector values to standard output }; #endif
- Vector.cpp
#include "Vector.hpp" Vector::Vector(int length) { size = length; array = new (nothrow) int[size]; if(array==NULL) { cerr << "Memory allocation failure!" << endl; exit(-1); } for(int i=0; i<size; i++) array[i] = 0; } Vector::Vector(const Vector &v) { size = v.length(); array = new (nothrow) int[size]; if(array==NULL) { cerr << "Memory allocation failure!" << endl; exit(-1); } for(int i=0; i<size; i++) array[i] = v.valueAt(i); } Vector::Vector(const Vector *v) { size = v->length(); array = new (nothrow) int[size]; if(array==NULL) { cerr << "Memory allocation failure!" << endl; exit(-1); } for(int i=0; i<size; i++) array[i] = v->valueAt(i); } Vector::~Vector() { delete [] array; } int Vector::length() const { return size; } int &Vector::valueAt(int pos) const { if(pos>=length()) { cerr << "Invalid access position!\n"; return array[size-1]; } return array[pos]; } int Vector::find(int a) const { for(int i=0; i<size; i++) if(array[i] == a) return i; return -1; } void Vector::print() const { for(int i=0; i<size; i++) { cout << array[i]; if(i==size-1) cout << endl; else cout << ", "; } }
- VectorUsage.cpp
#include "Vector.hpp" int main() { Vector v(5); v.valueAt(0) = 2; v.valueAt(1) = 3; v.valueAt(2) = 4; v.valueAt(3) = 5; v.valueAt(4) = 6; cout << "value 5 at position: " << v.find(5) << endl; cout << "value 10 at position: " << v.find(10) << endl; v.print(); }
Για την παραπάνω κλάση κλάση Vector θέλουμε να υπερφορτώσουμε τους τελεστές ανά κατηγορία ως εξής:
cpp/vector_overloading.1621841714.txt.gz · Last modified: 2021/05/24 06:35 (external edit)