#include <iostream>
using namespace std;
class A
{
private:
int a;
public:
A()
{
a=0;
}
A(int aa):a(aa){}//___(1)___{} 定义构造函数,用参数aa初始化数据成员a
};
main()
{
A *p;//___(2)___; 定义类A的指针对象p
p = new A(5);//___(3)__; 用p指向动态对象并初始化为整数
}
//b
#include <iostream>
using namespace std;
class A
{
private:
int *a;
int n;
int MaxLen;
public:
A(): a(0), n(0), MaxLen(0) {}
A(int *, int, int);//
~A();
int GetValue(int i) {return a[i];}
};
A::A(int *aa, int nn, int MM)
{
n = nn;
MaxLen = MM;
if (n > MaxLen) exit(1);
a = new int[MaxLen];
for (int i = 0; i < MaxLen; i++)//
*(a+i) = *(aa + i);//___(1)___; 以i为循环变量把aa数组中每个元素值传送给a数组的对应元素中
}
A::~A(){delete [] a;}//___(2)___ 析构函数的类外定义,释放指针型数据a所指向的空间
void main()
{
int b[10] = {1,2,3,4,5,6,7,8,9,10};
A r(b, 10, 10);
int i, s=0;
for (i = 0; i < 10; i++)
s += r.GetValue(i);//___(3)___ ; 以i为循环变量,把r对象的a数据成员中的每个元素值依次累加到s中
cout << "s=" << s << endl;
}
做这类问题要明确题目目的及要求