in-class initialization of non-const static member 'counter'

I tried to run this program, but it told me this, ISO C++ forbids in-class initialization of non-const static member ‘counter’. Basically I just wanna test if the counter will be increased if I create more ts objects. Is there some other way to get this? Thanks for helping.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;

class ts{
public:
  static int counter=0;
  ts(){counter++;};
  void printC(){
    cout<<counter<<endl;
  };

};

int main(){
  ts a;
  a.printC();
  ts b;
  b.printC();

  return 0;

}
Declare counter in the class body (line 6). static int counter;

And define it outside the class. int ts::counter = 0;
Last edited on
Topic archived. No new replies allowed.