以下是我在学静态成员时照例子写的一个程序
#include <iostream>
#include <iomanip>
using namespace std;
class StaticDemo
{
private:
static int counter;
public:
staticDemo();
~StaticDemo();
static void printCount();
};
StaticDemo::staticDemo()
{
counter++;
}
StaticDemo::~StaticDemo()
{
counter--;
cout<<"In destructor:counter: "<<counter<<endl;
}
void StaticDemo::printCount()
{
cout<<"Counter: "<<counter<<endl;
return;
}
int StaticDemo::counter=0;
int main()
{
cout<<"Start static demonstration.\n ";
StaticDemo a1;
cout<<"After first instantiation: ";
a1.printCount();
StaticDemo a2;
cout<<"After second instantiation: ";
StaticDemo::printCount();
cout<<"Terminating demonstration\n";
return 0;
}
在构造函数中,明明使counter++了,为什么输出的counter却始终是0,而析构函数正常,依次减了2次。