- #include <iostream>
- using namespace std;
- //定义类型A
- class A
- {
- public:
- friend class B; //类型B为友元类
- private:
- int **p; //指向二级数组
- int m_n1; //行数
- int m_n2; //列数
- public:
- A(int n1, int n2); //生成二维数据
- ~A();
- void InitA(); //初始化对象A
- };
- A::A(int n1, int n2)
- {
- m_n1 = n1; //记录二维数组行数
- m_n2 = n2; //记录二维数组列数
- p = new int* [n1];
- for(int i=0; i<n1; ++i)
- {
- p[i] = new int [n2];
- }
- }
- A::~A()
- {
- for (int i=0; i<m_n1; ++i)
- {
- delete[] p[i];
- }
- delete[] p;
- }
- void A::InitA()
- {
- for (int i=0; i<m_n1; ++i)
- {
- for (int j=0; j<m_n2; ++j)
- {
- p[i][j] = i*m_n2 + j;
- }
- }
- }
- //定义类型B
- class B
- {
- public:
- void Print(const A& a1);//打印二维数组内的元素
- };
- void B::Print(const A& a1)
- {
- for (int i=0; i<a1.m_n1; ++i)
- {
- for (int j=0; j<a1.m_n2; ++j)
- {
- cout << a1.p[i][j] << ' ';
- }
- cout << endl;
- }
- }
- int main()
- {
- A a(2, 4);
- a.InitA();
- B b;
- b.Print(a);
- }
- //-----------------------------------------------------------------
- //-----------------------------------------------------------------
- //-----------------------------------------------------------------
- //-----------------------------------------------------------------
- //C++里 数组new 和delete问题
- //对于数组new的不同方式 和不同的释放方法
- //----------------------------------------------------------------
- // 创建字符指针数组
- char **parr = new char*[100];
- for (int i=0;i<100;++i)
- {
- parr[i]=new char [50];
- }
- // 释放各个字符数组
- for (int i =0; i < 100; i++)
- delete [] parr[i];
- //释放字符指针数组
- delete [] parr;
- //---------------------------------------------------------------
- // 创建数组
- int *parr = new int[100];
- // 释放数组
- delete [] parr;