constructor class untuk pecahan

#include<iostream.h>

class pecahan {
        public :
          pecahan (int,int);
          void cetak ();
        private :
           int lang, but;
};
int main () {
        pecahan x(-1,3), y(22,7);
        cout<<" x = ";
        x.cetak();
        cout<<" dan y= ";
        y.cetak ();
        return 0;
}

pecahan::pecahan (int n, int d) {
       lang = n;
       but = d;
}
void pecahan::cetak () {
       cout<<lang<<'/'<<but:
}

penjelasan :

constructor initializes the object with a specific value on the data. at the time of declaration of x, constructors are called automatically by lintegers -1 and 3 received by the parameters n and d. then fill the function of the value to the member data of the object but lang and x. a declaration

fraction x (-1.3), y (22.7);

is comparable with the three lines

fractions x, y;
x. fill (-1.3);
y. fill (22.7);

class may have several constructors, like function overloading, constructors can be distinguished by looking at the difference of the arguments.

Leave reply

Back to Top