fork download
  1. // file my_complex.h
  2. class my_complex
  3. {
  4. public:
  5. my_complex(double r, double i);
  6.  
  7. double& real() { return r; }
  8. double& imaginary() { return i; }
  9. my_complex& add(double r, double i);
  10. my_complex& operator++();
  11. my_complex operator++(int);
  12. private:
  13. double r;
  14. double i;
  15. };
  16.  
  17. // file my_complex.cpp
  18. //#include "my_complex.h"
  19.  
  20. my_complex::my_complex(double r, double i) : r(r), i(i) { }
  21.  
  22. // returns reference the original object
  23. my_complex& my_complex::add(double r, double i) {
  24. this->r += r;
  25. this->i += i;
  26. return *this;
  27. }
  28.  
  29. // returns reference to the original (incremented) object
  30. my_complex& my_complex::operator++() {
  31. r += 1;
  32. return *this;
  33. }
  34.  
  35. // returns value with copy of the temporary object before incrementation
  36. my_complex my_complex::operator++(int) {
  37. my_complex orig(*this);
  38. r += 1;
  39. return orig;
  40. }
  41.  
  42. // file main.cpp
  43. int main()
  44. {
  45. my_complex c(6, 5); // default ctor
  46. double i = c.imaginary(); // copy returned reference
  47. c.real() = 8; // modify through returned reference
  48. ++(c.add(3, 4)); // chaining function calls on 'c'
  49. my_complex d = c++; // copy returned value
  50. return 0;
  51. }
Success #stdin #stdout 0s 3136KB
stdin
Standard input is empty
stdout
Standard output is empty