⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cpp29.cpp

📁 C++参考书
💻 CPP
字号:

// Coded by plusir -- Jan.04.2003.
// Standard C++ Bible -- (P337-12-29)

#include <iostream>
#include <string>
#include <cstddef>
#include <new>
using namespace std ;

const int maxnames = 5 ;

class Names
{
	public:
		Names( char * ) ;
		void* operator new( size_t ) throw( bad_alloc ) ;
		void operator delete( void * ) throw() ;
		void display( void ) const ;

	private:
		char name[25] ;
		static char pool[] ;
		static bool inuse[maxnames] ;
} ;

char Names::pool[maxnames * sizeof( Names )] ;
bool Names::inuse[maxnames] ;

Names::Names( char *s )
{
	strncpy( name, s, sizeof( name ) ) ;
}

void* Names::operator new( size_t ) throw( bad_alloc )
{
	for ( int p = 0; p < maxnames; ++p ) {
		if ( !inuse[p] ) {
			inuse[p] = true ;
			return pool + p * sizeof( Names ) ;
		}
	}
	throw bad_alloc() ;
}

void Names::operator delete( void *p ) throw()
{
	if ( p != 0 )
		inuse[( ( char* )p - pool ) / sizeof( Names )] = false ;
}

void Names::display( void ) const
{
	cout << name << endl ;
}

int main()
{
	Names * nm[maxnames] ;
	int i ;

	for ( i = 0; i < maxnames; ++i ) {
		cout << endl << "Enter name # " << i + 1 << ": " ;
		char name[25] ;
		cin >> name ;
		nm[i] = new Names( name ) ;
	}

	for ( i = 0; i < maxnames; ++i ) {
		nm[i]->display() ;
		delete nm[i] ;
	}

	return 0 ;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -