fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <cmath>
  5. #include <cassert>
  6.  
  7. using namespace std;
  8.  
  9. class LargeInteger {
  10. private:
  11. static int nextLargeIntegerId;
  12. int id;
  13. int numDigits; // number of digits in LargeInt / size of alloc array
  14. int* digits; // the digits of the LargeInt we are representing
  15.  
  16. public:
  17. LargeInteger(int value);
  18. ~LargeInteger();
  19. string tostring();
  20. };
  21.  
  22. LargeInteger::LargeInteger(int value)
  23. {
  24. // set this instance id
  25. id = nextLargeIntegerId++;
  26.  
  27. numDigits = (int)log10((double)value) + 1;
  28.  
  29. // allocate an array of the right size
  30. digits = new int[numDigits];
  31.  
  32. // iterate through the digits in value, putting them into our
  33. // array of digits.
  34. int digit;
  35. for (int digitIndex = 0; digitIndex < numDigits; digitIndex++) {
  36. // least significant digit
  37. digit = value % 10;
  38. digits[digitIndex] = digit;
  39.  
  40. // integer division to chop of least significant digit
  41. value = value / 10;
  42. }
  43. }
  44.  
  45. LargeInteger::~LargeInteger()
  46. {
  47. cout << " destructor entered, freeing my digits" << endl
  48. << " id = " << id << endl
  49. //<< " value=" << tostring() // uncomment this after you implement tostring()
  50. << endl;
  51. delete[] this->digits;
  52. }
  53.  
  54. string LargeInteger::tostring()
  55. {
  56. string intValue;
  57. for (int i=numDigits-1; i>=0; i--)
  58. intValue += digits[i] + '0';
  59. return intValue;
  60. }
  61.  
  62. int LargeInteger::nextLargeIntegerId = 0;
  63.  
  64. int main() {
  65. // test constructors, destructors and tostring()
  66. cout << "Testing Constructors, tostring() and destructor:" << endl;
  67. cout << "-------------------------------------------------------------" << endl;
  68. LargeInteger li1(3483);
  69. cout << "li1 = " << li1.tostring() << endl;
  70.  
  71. return 0;
  72. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Testing Constructors, tostring() and destructor:
-------------------------------------------------------------
li1 = 3483
 destructor entered, freeing my digits
 id = 0