[ create a new paste ] login | about

Link: http://codepad.org/3cIgObOk    [ raw code | output | fork ]

C++, pasted on Feb 20:
#include <iostream>
#include <memory>
 
#include <cstring>	


//定義一個Baseball的類別
class BaseballPlayer 
{
    private: enum
    {
        MAX_STRING_LENGTH = 20    
    }; 
    //定義私用資料及函式成員
    private: char name[ MAX_STRING_LENGTH + 1 ];         //打擊者姓名         
    private: int fires;                                  //打擊次數
    private: int safes;                                  //安打次數
    //宣告私用的函數成員countsafe的原型用以計算打擊者打擊率
	
    //定義公用資函數成員
    public: BaseballPlayer( char const *theName, int theFires, int theSafes )
    : fires( theFires ), safes( theSafes ) 
    {
        ::strncpy( name, theName, MAX_STRING_LENGTH );
    }
	
	// 拷貝建構子
    public: BaseballPlayer( BaseballPlayer const &player )
    : fires( player.fires ), safes( player.safes ) 
    {
        ::strncpy( name, player.name, MAX_STRING_LENGTH );
    }    
     
    public: std::ostream& show( std::ostream &outputStream );
    //宣告公用的函式數成員inputplayer的原型用以顯示打擊者資料

};

std::ostream& BaseballPlayer::show( std::ostream &outputStream )          //類別外實現showplayer函式成員
{
	
    //透過countsafe 函式成員計算並傳回打擊率
    outputStream << "================================" << std::endl;
    outputStream << "打擊者:" << name << std::endl;     //顯示打擊者姓名
    outputStream << "打擊次數:" << fires << std::endl;    //顯示打擊次數
    outputStream << "安打次數:" << safes << std::endl;    //顯示安打次數
    
    return outputStream; 
}


int main()
{
    using namespace std;
    // 還沒好建構物件
    char rawMemory[ 2 * sizeof(BaseballPlayer) ]; 
    BaseballPlayer *b = reinterpret_cast<BaseballPlayer*>( rawMemory );
    // 逐一喚起建構子 
    std::uninitialized_fill( b, b + 2, BaseballPlayer( "qq", 100, 2 ) ); 
     
    cout << "================================" << endl;
    cout << "顯示資料" << endl;
    for ( int i = 0; i < 2; ++i )  
    {
        b[ i ].show( cout );
    }
	
    // 呼叫解構子摧毀物件 
    for( int index = 0; index != 2; ++index ) 
       b[ index ].~BaseballPlayer();
        
    cin.get();
}	


Output:
1
2
3
4
5
6
7
8
9
10
================================
顯示資料
================================
打擊者:qq
打擊次數:100
安打次數:2
================================
打擊者:qq
打擊次數:100
安打次數:2


Create a new paste based on this one


Comments: