设计一个类,用对象数组,堆对象和对象拷贝建立该类的对象,统计建立的对象数
怎么来设计解决这个
堆对象?就是new出来呗?对象数组是存储这个设计出来的类?
是要这样吗?
#include <iostream>
using namespace std;
class A
{
protected:
static int count;
int n;
public:
A() {count++;}
A(int n):n(n) {count++;}
A(const A& a) {n = a.n;count++;}
static int getCount() {return count;}
};
int A::count = 0;
int main()
{
int n,m=0;
A *p = NULL;
A as[10];
cin>>n;
while(n>0)
{
if(n!=m)
{
A *a = new A(n);
p = a;
m = n;
}
else
A *a = new A(*p);
cin>>n;
}
cout<<"共创建"<<A::getCount()<<"个A对象"<<endl;
return 0;
}
用各种方式(对象数组,堆对象,对象拷贝)建立该类的对象
#include <iostream>
class Object {
public:
Object() { _count++; }
Object(const Object &) { _count++; }
~Object() { _count--; }
static int count() { return _count; }
private:
static int _count;
};
int Object::_count = 0;
int main() {
// Create an object in the heap.
Object *p = new Object;
// Create an object by copying the existing object.
Object q = *p;
// Create an array of 5 objects.
Object obj[5];
// Output the total number of created objects, which should be 7.
std::cout << Object::count() << '\n';
delete p;
return 0;
}