C++ examples for Class:Member Function
Add accessor function to read member field
#include <iostream> using namespace std; // declaration section class Complex/*w w w . j a v a2 s.c om*/ { private: double realPart; double imaginaryPart; public: Complex(double real = 0.0, double imag = 0.0) // inline constructor { realPart = real; imaginaryPart = imag; } void showComplexValues(); // accessor prototype void assignNewValues(double real, double imag) // inline mutator { realPart = real; imaginaryPart = imag; } Complex multScaler(double = 1.0); }; void Complex::showComplexValues() // accessor { char sign = '+'; if (imaginaryPart < 0) sign = '-'; cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i'; } Complex Complex::multScaler(double factor) { Complex newNum; newNum.realPart = factor * realPart; newNum.imaginaryPart = factor * imaginaryPart; return newNum; } int main() { Complex complexOne(12.57, 18.26), complexTwo; // declare two objects cout << "The value assigned to complexOne is "; complexOne.showComplexValues(); complexTwo = complexOne.multScaler(10.0); // call the function cout << "\nThe value assigned to complexTwo is "; complexTwo.showComplexValues(); return 0; }