C++ examples for Class:Member Function
Using a function with a reference parameter in the Integer class
#include <iostream> class Integer//from w w w . ja v a2 s . co m { private: int n; public: Integer(int m = 0); Integer(Integer& obj); // Copy constructor int compare(const Integer& obj) const; // Compare function with reference paramter int getValue() {return n;} void setValue(int m){ n = m; } void show(); }; // Copy constructor Integer::Integer(Integer& obj) : n(obj.n) { std::cout << "Object created by copy constructor." << std::endl; } // Constructor Integer::Integer(int m) : n(m) { std::cout << "Object created." << std::endl; } void Integer::show() { std::cout << "Value is " << n << std::endl; } // Compare function with reference parameter int Integer::compare(const Integer& obj) const { if(n < obj.n) return -1; else if(n==obj.n) return 0; return 1; } int main(){ std::cout << "Create i with the value 10." << std::endl; Integer i {10}; i.show(); std::cout << "Change value of i to 15." << std::endl; i.setValue(15); i.show(); std::cout << "Create j from object i." << std::endl; Integer j {i}; j.show(); std::cout << "Set value of j to 150 times that of i." << std::endl; j.setValue(150*i.getValue()); j.show(); std::cout << "Create k with the value 300." << std::endl; Integer k {300}; k.show(); std::cout << "Set value of k to sum of i and j values." << std::endl; k.setValue(i.getValue()+j.getValue()); k.show(); std::cout << "Result of comparing i and j is " << i.compare(j) << std::endl; std::cout << "Result of comparing k and j is " << k.compare(j) << std::endl; }