Use of static in Classes in C++ can bee seen through following program.
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
class UniquelyIdentified{
public:
UniquelyIdentified();
const int getUniqueID() const;
private:
static int ID;
};
int UniquelyIdentified::ID = 0;
int main(){
cout << "Press 'c' to create new Object, -1 to exit" << endl;
char opt;
while ((cin>>opt) && (opt=='c')){
UniquelyIdentified obj;
cout << "Get ID? (y/n) ";
char o;
if ((cin >> o) && (o=='y')){
cout << "ID of current Object: " << obj.getUniqueID() << endl;
}
}
return 0;
}
UniquelyIdentified::UniquelyIdentified(){
ID++;
}
const int UniquelyIdentified::getUniqueID() const{
return ID;
}
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
class UniquelyIdentified{
public:
UniquelyIdentified();
const int getUniqueID() const;
private:
static int ID;
};
int UniquelyIdentified::ID = 0;
int main(){
cout << "Press 'c' to create new Object, -1 to exit" << endl;
char opt;
while ((cin>>opt) && (opt=='c')){
UniquelyIdentified obj;
cout << "Get ID? (y/n) ";
char o;
if ((cin >> o) && (o=='y')){
cout << "ID of current Object: " << obj.getUniqueID() << endl;
}
}
return 0;
}
UniquelyIdentified::UniquelyIdentified(){
ID++;
}
const int UniquelyIdentified::getUniqueID() const{
return ID;
}
No comments:
Post a Comment