Consider the following code:
#include <iostream>
class CTest
{
public:
CTest() : c(0)
{}
void Method1()
{
c++;
std::cout<<"c: "<<c<<std::endl;
}
private:
int c;
};
int main()
{
CTest A,B,C;
A.Method1();
B.Method1();
C.Method1();
return 0;
}
c: 1
c: 1
c: 1
for each object of this type, the c value is different. To avoid name conflict, I am interested to put the c variable inside the function since Method1 is the only place where it is supposed to be used. My concern is how to make it independent for each different object. Is there any built-in C++ solution?
#include <iostream>
class CTest
{
public:
CTest()
{}
void Method1()
{
static int c=0;
c++;
std::cout<<"c: "<<c<<std::endl;
}
private:
};
int main()
{
CTest A,B,C;
A.Method1();
B.Method1();
C.Method1();
return 0;
}
c: 1
c: 2
c: 3
Aucun commentaire:
Enregistrer un commentaire