Jumat, 16 Maret 2012

Data Structures Servies(Basic)

Step to OOP (Step 5)
Data Structures Series [Basics]
Final Touch with I/O Overloading

Finally, we will complete the "part" class is useful when we will develop a user interface that is implemented using operator>> (access cin) and operator <<(court access) associated with the object that is defined as the instant of the class.

Why are said to be "part" of the class? YES, because it really is not a member of the class, but still can access the private data in particular. It is a friend of that class.
 

Step 1:
Array initialization we replace with input through keyboard


Step 2:
print_array () methods is replaced with output operator overloading the following :


Step 3:
Class changed to:



Complete the program becomes:

#include
#include
using namespace std;

class MyArray {
friend istream& operator>>(istream&, MyArray&);
friend ostream& operator<<(ostream&, const MyArray&);
public:
MyArray();
void minus_one();
private:
int n;
int A[10];
};

istream& operator>>(istream& input, MyArray& Mine) {
for (int i=0; i
cout << "Enter the data : ";
input >> Mine.A[i];
}
return input;
}

ostream& operator<<(ostream& output, const MyArray& Mine) {
for (int i=0; i < Mine.n; i++)
cout << "A[" << i << "] is " << Mine.A[i] << endl;
getch();
return output;
}

MyArray::MyArray() {
cout << "Welcome to OOP ... \n";
n = 10;
}

void MyArray::minus_one() {
for (int i=0; i < n; i++)
A[i]--;
}

int main(int argc, char *argv[]) {
MyArray mine;
cin >> mine;
cout << "Initial array is : " << endl;
cout << mine;
mine.minus_one();
cout << "After -1 be : " << endl;
cout << mine;
system("PAUSE");
return EXIT_SUCCESS;
}

Tidak ada komentar: