类的封装
# ifndef ARRAY_H
# define ARRAY_H
class DoubArray
{
private :
int m_length;
double * m_pointer;
public :
DoubArray ( int len) ;
DoubArray ( const DoubArray& obj) ;
int length ( ) ;
bool get ( int index, double & value) ;
bool set ( int index, double value) ;
void sort ( const DoubArray& obj) ;
void show ( const DoubArray& obj) ;
~ DoubArray ( ) ;
} ;
# endif
类的实现
# include "Array.h"
# include <iostream>
using namespace std;
DoubArray :: DoubArray ( int len)
{
m_pointer = new double [ len] ;
for ( int i = 0 ; i < len; i++ )
{
m_pointer[ i] = 0 ;
}
m_length = len;
}
DoubArray :: DoubArray ( const DoubArray& obj)
{
m_length = obj. m_length;
m_pointer = new double [ obj. m_length] ;
for ( int i = 0 ; i < obj. m_length; i++ )
{
m_pointer[ i] = obj. m_pointer[ i] ;
}
}
void DoubArray :: sort ( const DoubArray& obj)
{
int len = obj. m_length;
for ( int i = 0 ; i < len; i++ )
{
for ( int j = 0 ; j < len - i; j++ )
{
if ( obj. m_pointer[ j] < obj. m_pointer[ j+ 1 ] )
{
double temp = obj. m_pointer[ j] ;
obj. m_pointer[ j] = obj. m_pointer[ j+ 1 ] ;
obj. m_pointer[ j+ 1 ] = temp;
}
}
}
}
int DoubArray :: length ( )
{
return m_length;
}
bool DoubArray :: get ( int index, double & value)
{
bool ret = ( 0 <= index) && ( index < length ( ) ) ;
if ( ret )
{
value = m_pointer[ index] ;
}
return ret;
}
bool DoubArray :: set ( int index, double value)
{
bool ret = ( 0 <= index) && ( index < length ( ) ) ;
if ( ret )
{
m_pointer[ index] = value;
}
return ret;
}
void DoubArray :: show ( const DoubArray& obj)
{
int len = obj. m_length;
for ( int i = 0 ; i < len ; i++ )
{
cout << obj. m_pointer[ i] << endl;
}
}
DoubArray :: ~ DoubArray ( )
{
delete [ ] m_pointer;
}
主函数调用
# include <iostream>
# include "Array.h"
using namespace std;
int main ( )
{
double score = 0 ;
int num = 0 ;
cout << "请输入学生人数:" ;
cin >> num;
DoubArray stu_a ( num) ;
for ( int i = 0 ; i < num; i++ )
{
cout << "请输入第" << i+ 1 << "个学生的成绩:" ;
cin >> score;
stu_a. set ( i, score) ;
}
cout << "学生成绩降序排列如下:" ;
stu_a. sort ( stu_a) ;
stu_a. show ( stu_a) ;
return 0 ;
}
程序效果