fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <assert.h>
  4.  
  5. using namespace std;
  6.  
  7. void print(float t) {cout << t << endl;}
  8.  
  9.  
  10. class array {
  11. public:
  12.  
  13. size_t size;
  14. float *data;
  15.  
  16. // constructor
  17. array(int m)
  18. {
  19. size = m;
  20. data = new float[size];
  21. }
  22. // destructor
  23. ~array()
  24. {
  25. delete [] data;
  26. }
  27.  
  28. friend void swap(array& first, array&second)
  29. {
  30. using std::swap;
  31. swap(first.data,second.data);
  32. swap(first.size,second.size);
  33. }
  34.  
  35. //! copy constructor
  36. array(const array& other): size(other.size), data(size ? new float[size]:0)
  37. {
  38. std::copy(other.data, other.data + size, data);
  39. }
  40.  
  41. // move constructor
  42. array(array&& other)
  43. {
  44. swap(*this,other);
  45. }
  46.  
  47. //! copy assignment
  48. array& operator=(array other)
  49. {
  50. swap(*this,other);
  51. return *this;
  52. }
  53.  
  54. // operator- between two arrays
  55. const array operator-(const array& other)
  56. {
  57. assert(size==other.size && "Cannot add array of different sizes!");
  58. array tmp(other.size);
  59. for (size_t i=0;i<size;++i)
  60. tmp.data[i] = data[i]-other.data[i];
  61.  
  62. return tmp;
  63. }
  64.  
  65. void fill(const float& num)
  66. {
  67. std::fill(data,data+size,num);
  68. }
  69. };
  70.  
  71.  
  72. array operator -(float lhs, const array& rhs)
  73. {
  74. array tmp(rhs.size);
  75. for (size_t i=0;i<rhs.size;++i)
  76. tmp.data[i] = lhs-rhs.data[i];
  77. cout << "called first overload" << endl;
  78. return tmp;
  79. }
  80.  
  81. array operator -( array& lhs, float rhs)
  82. {
  83. array tmp(lhs.size);
  84. for (size_t i=0;i<lhs.size;++i)
  85. tmp.data[i] = lhs.data[i]-rhs;
  86. cout << "called second overload" << endl;
  87. return tmp;
  88. }
  89.  
  90. void print(const array& t) {
  91. for (size_t i=0;i<t.size;++i)
  92. cout << t.data[i] << " ";
  93. cout << endl;
  94. }
  95.  
  96.  
  97.  
  98. int main()
  99. {
  100. array f(5);
  101. f.fill(13.4);
  102. print(f);
  103.  
  104. print(2-f-5);
  105. print(2-(f-5));
  106.  
  107. cout << "All Good!" << endl;
  108. return 0;
  109. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
13.4 13.4 13.4 13.4 13.4 
called first overload
-11.4 -11.4 -11.4 -11.4 -11.4 
called second overload
called first overload
-6.4 -6.4 -6.4 -6.4 -6.4 
All Good!