SIMPLE QUESTION

Hey Guys I have a simple question on this. Now all I can do is editing the class only , the main function need to remain and any solution for this??? Thanks!!!

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

class AA {
int x;
public:
    AA(int x);
    int getX(){return x;}
};

int main(){
cout << AA::getX() <<endl;
AA* a = new AA[100];
cout << AA::getX() <<endl;
delete []a;
cout << AA::getX() <<endl;
}
If you rewrite the class as follows it will build and run. Is that what you want?

1
2
3
4
5
class AA {
public:
    AA(){};
   static  int getX(){return 7;}
};
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

class AA {
static int x;
public:
    AA(){x;}
    static int getX(){return x;}
};
int AA::x = 0;

int main(){
cout << AA::getX() <<endl;
AA* a = new AA[100];
cout << AA::getX() <<endl;
delete []a;
cout << AA::getX() <<endl;
}


I use the static attribute which you are using just now and now it can compile and run but the output is
0
0
0

and the expected output is..
0
100
0

So I need to create a new contructor for it or??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

class AA {
static int x;
public:
    AA(){++x;}
    ~AA(){--x;}
    static int getX(){return x;}
};
int AA::x = 0;

int main(){
cout << AA::getX() <<endl;
AA* a = new AA[100];
cout << AA::getX() <<endl;
delete []a;
cout << AA::getX() <<endl;
}


Thanks Moschops I fixed the problem!!! Thanks again for helping me!
Topic archived. No new replies allowed.