C++ examples for Class:Member Function
Add inline member function to change member field value
#include <iostream> #include <cmath> using namespace std; // declaration section class Complex/*from ww w .j av a2s . c o m*/ { private: double realPart; // declare realPart as a double variable double imaginaryPart; // declare imaginaryPart as a double variable public: Complex(double = 0.0, double = 0.0); // constructor prototype void showComplexValues(); // accessor prototype void assignNewValues(double real, double imag) // inline mutator {realPart = real; imaginaryPart = imag;} double amplitude() { return (sqrt(pow(realPart,2) + pow(imaginaryPart,2))); } }; // end of class declaration // implementation section Complex::Complex(double real, double imag) // constructor { realPart = real; imaginaryPart = imag; cout << "Created a new complex number object.\n"; } void Complex::showComplexValues() // accessor { char sign = '+'; if (imaginaryPart < 0) sign = '-'; cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i'; } int main() { Complex complexOne(3.0, 4.0); // declare a variable of type Complex cout << "The value assigned to this complex object is "; complexOne.showComplexValues(); cout << "\n\nThe amplitude of this complex number is " << complexOne.amplitude() << endl; return 0; }