这次写代码还是感觉自机不够细心,自己太马虎,虽然不是一名程序员但应该做好自己。
派生类继承要点:
总结: B 基类 D 派生类
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1.若D有构造函数而B没有,创建D类的对象时,D的构造函数会被自动调动。
2.若D没有构造函数而B有,则B必须拥有默认构造函数。只有这样,创建D类的对象时,才能自行执行B的默认构造函数。
3若D有构造函数,且B拥有默认构造函数,则创建D类的对象时,B的默认构造函数会被自动执行,除非当前被调用的派生类构造函数显式的调用了B的默认的构造函数。
4若D和B都有构造函数,但B没有默认构造函数,则D的每个构造函数必须在其初始化阶段中显式的调用B的构造函数。只有这样,创建D的对象时,B的构造函数才能获得执行机会。
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
即:创建派生类对象时,必须显式或者隐式的执行基类的某个构造函数。
头文件:
#ifndef ARRAY_H_
#define ARRAY_H_
#define MAX_ARRAY 50 // 设置最大数组存取长度
#define len(a) (sizeof(a)/sizeof(a[0])) // 计算数组长度
#include <iostream>
#include <cstdlib> // use exit();
using namespace std;
class int_array{
public:
int_array(): n(0) {cout << "please initlization to use \n";}
int_array(const int* ara, int length_array){
copy_array(ara, length_array);
}
~int_array(){};
void add_array(const int* ara, int length_array){
copy_array(ara, length_array);
}
void ini_array(const int* ara, int length_array){
copy_array(ara, length_array);
}
void print();
int print(const int &);
protected:
int ar[MAX_ARRAY]; // 缓冲区
int n = 0 ; // 缓冲区数组长度
void copy_array(const int* ,const int& ); // 将数组复制到缓冲区
};
class matrix : public int_array{
public:
matrix(const int* arr, const int length_array) : int_array(arr, length_array){
col_count = length_array;
row_count ++;
}
void init_matrix( const int*arr){
copy_array(arr, col_count);
row_count ++;
}
void print();
int print(const int& , const int& );
private:
int row_count = 0;
int col_count = 0;
};
#endif // ARRAY_H_
头文件的实现文件
#include "array.h"
using namespace std;
void int_array::print(){
for(int i=0; i<n; i++){
cout << ar[i] << ' ';
}
cout << endl;
}
int int_array::print(const int& n){
if(n<1 || n > this->n+1){
cout << "XXXXXXX" << endl;
exit(0);
}
cout << "the element " << n << " of is : " << ar[n-1] << endl;
return ar[n-1];
}
void int_array::copy_array(const int* a, const int& length_array){
for(int i=0; i<length_array; i++){
ar[i+n] = a[i];
}
n += length_array;
}
void matrix::print(){
for(int row=0; row<row_count; row++){
for(int col=0; col<col_count; col++){
cout << ar[row*row_count+col] << ' ';
}
cout << endl;
}
}
int matrix::print(const int& row, const int& col){
if(row-1 < 0 || row-1>row_count || col-1<0 || col-1>col_count){
cout << "xxxxxxxxx" << endl;
exit(0);
}
cout << "the <" << row << ":" << col << "> of matrix is : "<< ar[(row-1)*(col-1)+col-1] << endl;
return ar[(row-1)*(col-1)+col-1];
}
测试程序:
#include "array.h"
int main()
{
int a[5] = {1,2,3,4,5};
int b[5] = {7,8,9,10,11};
int_array t(a, 5);
t.print();
t.print(2);
t.add_array(b, 3);
t.print();
t.print(1);
// matrix x;
matrix v(a, 5);
v.init_matrix(b);
v.print();
v.print(1,1);
return 0;
}
结果: