C和C++语言&

#include "stdafx.h"
#include "iostream"
#include "animal.h"
using namespace std;
#include <iostream>
using namespace std;


class Array
{
public:
Array(unsigned int s);
~Array();
//当析构函数不是虚函数时,???
virtual void add(int e);
//基类的成员函数不是虚函数时,派生类调用基类的成员函数
//基类的成员函数是虚函数时,子类调用派生类的成员函数
int get(unsigned int i) const;
protected:
int* a;
unsigned int size, num;
};
class sortedArray:public Array
{
public:
sortedArray(unsigned int s);
~sortedArray();
//基类要定义了虚函数 子类也需要定义虚函数吗?
void add(int e);
private:

};


Array::Array(unsigned int s)
{
size = s;
num = 0;
a = new int[s];
}

Array::~Array()
{
//delete[] a;
}

void Array::add(int e)
{
if (num<size)
{
a[num] = e;
num++;
}
}

int Array::get(unsigned int i) const
{
if (i<size)
{
return a[i];
}
return 0;
}


//子类
sortedArray::sortedArray(unsigned int s) :Array(s)
{
}

sortedArray::~sortedArray()
{
}
void sortedArray::add(int e)
{
if (num >= size)
{
return;
}
int i = 0, j;
if (i < num)
{
if (e < a[i])
{
for (j = num; j > i; j--)
{
a[j] = a[j - 1];
}
a[i] = e;
//break;
}
/*i++;*/
}
if (i == num)
{
a[i] = e;

}
num++;
}
void fun(Array& b)
{
int i;
for (i = 10; i >= 1; i--)
{
b.add(i);
}
for (i = 0; i < 10; i++)
{
cout << b.get(i)<< ",";
}
cout << endl;
}
//析构函数是对象在结束自己的生命周期时,系统自动调用析构函数
//问题1.出现野指针。问题2.sa调用派生类sortArray的add时结果调用的是基类Array的add函数
//问题3.出现了4次析构函数说明结束了4次生命周期

int _tmain()
{
Array a(10);
fun(a);


sortedArray sa(10);

fun(sa);
return 0;
}

原文地址:https://www.cnblogs.com/huninglei/p/5329147.html