📄 cpp30.cpp
字号:
// Coded by plusir -- Jan.05.2003.
// Standard C++ Bible -- (P340-11-30)
#include <iostream>
#include <string>
#include <cstddef>
#include <new>
using namespace std ;
const int maxnames = 5 ;
class Names
{
public:
Names( char *s = NULL )
{
if ( s )
strncpy( name, s, sizeof( name ) ) ;
}
void* operator new[] ( size_t ) throw( bad_alloc ) ;
void operator delete[] ( void* ) throw() ;
void display( void ) const
{ cout << name << endl ; }
private:
char name[25] ;
static char pool[] ;
static short int inuse[maxnames] ;
} ;
char Names::pool[maxnames * sizeof( Names )] ;
short int Names::inuse[maxnames] ;
void* Names::operator new[] ( size_t size ) throw( bad_alloc )
{
int elements = size / sizeof( Names ) ;
for ( int p = 0; p < maxnames; ++p ) {
if ( !inuse[p] ) {
int i ;
for ( i = 0; i < elements && p + i < maxnames; ++i )
if ( inuse[p + i] )
break ;
if ( i == elements && p + i < maxnames ) {
for ( i = 0; i < elements; ++i )
inuse[p + i] = elements ;
return pool + p * sizeof( Names ) ;
}
}
}
throw bad_alloc() ;
}
void Names::operator delete[] ( void *b ) throw()
{
if ( b != NULL ) {
int p = ( ( char* )b - pool ) / sizeof( Names ) ;
int elements = inuse[p] ;
for ( int i = 0; i < elements; ++i )
inuse[p + i] = 0 ;
}
}
int main()
{
Names* np = new Names[maxnames + 1] ;
int i ;
for ( i = 0; i < maxnames; ++i ) {
cout << endl << "Enter name # " << i + 1 << ": " ;
char name[25] ;
cin >> name ;
*( np + i ) = name ;
}
for ( i = 0; i < maxnames; ++i )
( np + i )->display() ;
delete [] np ;
return 0 ;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -