cpp:operator_overloading
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
cpp:operator_overloading [2017/04/26 14:27] – gthanos | cpp:operator_overloading [2017/05/04 12:20] – gthanos | ||
---|---|---|---|
Line 95: | Line 95: | ||
Οι τελεστές που δεν υπερφορτώνονται είναι οι εξής: | Οι τελεστές που δεν υπερφορτώνονται είναι οι εξής: | ||
| :: | .* | . | ?: | | | :: | .* | . | ?: | | ||
+ | |||
+ | ===== Παράδειγμα Υπερφόρτωσης Τελεστών ===== | ||
+ | |||
+ | Ας υποθέσουμε ότι έχουμε την παρακάτω κλάση //Vector// η οποία υλοποιεί ένα μονοδιάστατο πίνακα από ακεραίους. | ||
+ | <code cpp Vector.cpp> | ||
+ | #include < | ||
+ | #include < | ||
+ | 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 & | ||
+ | int find(int a); | ||
+ | }; | ||
+ | |||
+ | Vector:: | ||
+ | size = length; | ||
+ | array = new (nothrow) int[size]; | ||
+ | if(array==NULL) { | ||
+ | cerr << " | ||
+ | exit(-1); | ||
+ | } | ||
+ | for(int i=0; i<size; i++) | ||
+ | array[i] = 0; | ||
+ | } | ||
+ | |||
+ | Vector:: | ||
+ | size = v.length(); | ||
+ | array = new (nothrow) int[size]; | ||
+ | if(array==NULL) { | ||
+ | cerr << " | ||
+ | exit(-1); | ||
+ | } | ||
+ | for(int i=0; i<size; i++) | ||
+ | array[i] = v.valueAt(i); | ||
+ | } | ||
+ | |||
+ | Vector:: | ||
+ | size = v-> | ||
+ | array = new (nothrow) int[size]; | ||
+ | if(array==NULL) { | ||
+ | cerr << " | ||
+ | exit(-1); | ||
+ | } | ||
+ | for(int i=0; i<size; i++) | ||
+ | array[i] = v-> | ||
+ | } | ||
+ | |||
+ | Vector:: | ||
+ | delete [] array; | ||
+ | } | ||
+ | |||
+ | unsigned int Vector:: | ||
+ | return size; | ||
+ | } | ||
+ | |||
+ | int & | ||
+ | if(pos> | ||
+ | cerr << " | ||
+ | | ||
+ | } | ||
+ | return array[pos]; | ||
+ | } | ||
+ | |||
+ | int Vector:: | ||
+ | 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//. | ||
+ |
cpp/operator_overloading.txt · Last modified: 2021/05/24 06:28 (external edit)