课后习题1答案

想要知道答案的小伙伴们看过来哟:

  • 题目
写出类A的定义,通过类的静态成员来记录已经创建的A类的实例(对象)的个数,使得下面的程序
int main()
{
    A *pA = new A[10];
    cout<<"There are"<<pA->GetObjCount()<<"objects"<<endl;
    delete []pA;
    cout<<"There are"<<A::GetObjCount()<<"objects"<<endl;
    return 0;
}
得到的输出为:
There are 10 objects
There are 0 objects

  • 答案
class A
{ 
private:
    static int num;
public:
    A() { num++;}
    ~A(){ num--;}
    static int GetObjCount(){ return num; }
};
int A::num = 0;
  • 完整程序
#include<iostream>
using namespace std;
class A
{ 
private:
    static int num;
public:
    A() { num++;}
    ~A(){ num--;}
    static int GetObjCount();//GetObjCount()
};
int A::num = 0;//对静态数据成员进行初始化(只能在类外用参数初始化列表对静态数据成员进行初始化)
A::GetObjCount()
{
    return num;
}
int main()
{
    A *pA=new A[10];//A a;
    cout<<"There are "<<pA->GetObjCount()<<" objects"<<endl;
        delete []pA;
    cout<<"There are "<<A::GetObjCount()<<" objects"<<endl;//A::GetObjCount()说明GetObjCount()是静态成员函数
        return 0;
}

结果如图所示:
运行结果

习题原文链接:https://blog.csdn.net/HuaCode/article/details/80028074

猜你喜欢

转载自blog.csdn.net/huacode/article/details/80032628