cpp:vector_overloading
This is an old revision of the document!
Table of Contents
Παράδειγμα Υπερφόρτωσης Τελεστών
Ας υποθέσουμε ότι έχουμε την παρακάτω κλάση Vector η οποία υλοποιεί ένα μονοδιάστατο πίνακα από ακεραίους.
- Vector.cpp
#include <iostream> #include <cstdlib> using namespace std; class Vector { int *array; unsigned int size; public: Vector(unsigned int length=0); Vector(const Vector &v); Vector(const Vector *v); ~Vector(); unsigned int length() const; int &valueAt(unsigned int pos) const; int find(int a); }; Vector::Vector(unsigned 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; } unsigned int Vector::length() const { return size; } int &Vector::valueAt(unsigned int pos) const { if(pos>=length()) { cerr << "Invalid access position!\n"; return array[size-1]; } return array[pos]; } int Vector::find(int a) { for(int i=0; i<size; i++) if(array[i] == a) return i; return -1; } 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; }
Για την παραπάνω κλάση κλάση Vector θέλουμε να υπερφορτώσουμε τους τελεστές ως εξής:
Μοναδιαίοι τελεστές (unary operators)
Τελεστής | Θέση (πριν ή μετά το αντικείμενο) | Περιγραφή |
---|---|---|
+ | Πριν | Επιστρέφει το άθροισμα των στοιχείων του αντικειμένου |
- | Πριν το αντικείμενο | Επιστρέφει ένα νέο αντικείμενο τα στοιχεία του οποίου έχουν αντεστραμμένο πρόσημο σε σχέση με το αντικείμενο που εφαρμόζεται. |
cpp/vector_overloading.1493900942.txt.gz · Last modified: 2017/05/04 11:29 (external edit)