Problem description:
1 + 2 +... + N. the keyword such as multiplication and division, for, while, if, else, switch, and Case and the condition judgment statement (? B: C ).
Analysis:
Use static variables of the class to implement:If new contains N arrays of this type, the constructor of this class will be called N times.
Code implementation:
1 // 12.cc 2 #include <iostream> 3 using namespace std; 4 5 class Object { 6 public: 7 Object() { 8 ++N; 9 Sum += N;10 }11 static void reset() { N = 0; Sum = 0; }12 static int get_sum() { return Sum; }13 14 private:15 static int N;16 static int Sum;17 };18 19 int Object::N = 0;20 int Object::Sum = 0;21 22 int sum(int n) {23 Object::reset();24 25 Object* a = new Object[n];26 27 delete []a;28 a = 0;29 30 return Object::get_sum();31 }32 33 int main() {34 int n = 10;35 cout << "The sum is: " << sum(n) << endl;36 return 0;37 }