【CPPTraining】Techniques towards Less Coding PA

      培训内容简要回顾

      1)函数与函数的重载

            a)什么是函数

            b)函数的声明

            c)函数的默认参数

            d)函数的重载

      2)从宏到常量与内联函数

            a)宏

            b)C++中的常量

            c)C++中的内联函数

      3)运算符与运算符重载

            a)运算符有哪些

            b)对标准库一些现象的思考

            c)运算符的重载

      4)组成和继承(Optional)

      5)多态与虚函数(Optional)

      参考资料(Links)

      1)函数重载及默认参数

      2)常量

      3)内联函数

      4)运算符重载

      5)C++标准I/O库中的继承关系

【CPPTraining】Techniques towards Less Coding PA_第1张图片

      编程练习题目

【CPPTraining】Techniques towards Less Coding PA_第2张图片

【CPPTraining】Techniques towards Less Coding PA_第3张图片

【CPPTraining】Techniques towards Less Coding PA_第4张图片

【CPPTraining】Techniques towards Less Coding PA_第5张图片

【CPPTraining】Techniques towards Less Coding PA_第6张图片

【CPPTraining】Techniques towards Less Coding PA_第7张图片

      程序的输入

// Same as the previous section~

      一种实现的方式

      main.cpp

#include <iostream>

// Informing the complier the
// contact book you have written 
#include "ContactBook.h"

// Test script for the class
int main()
{
    // Declare a object representing the contact book

    ContactBook myContactBook;
    ContactBook myNewContactBook;
    const std::string szContactBookPath = "./Contact.txt";
    const std::string szOutputContactBookPath = "./ContactModified.txt";

    // Load the contact book

    std::cout << "Load contact book from file " 
	          << szContactBookPath << "..." << std::endl;

    myContactBook.loadContactBook( szContactBookPath );

    std::cout << std::endl;

    //////////////////////////////////////////////////////////////////////////

    // Display all contact infomation

    std::cout << "Display contact book..." << std::endl;

    myContactBook.display();

    std::cout << std::endl;

    //////////////////////////////////////////////////////////////////////////

    // Display sigle contact infomation

    std::cout << "Display POSONG's contact information..." << std::endl;

    myContactBook.display( "POSONG" );

    std::cout << std::endl;

    //////////////////////////////////////////////////////////////////////////

    // Update POSONG's contact information

    std::cout << "Update POSONG's contact information..." << std::endl;

    ContactInfo infoToUpdate;
    infoToUpdate.nInstructorNO = 1;
    infoToUpdate.szName = "POSONG";
    infoToUpdate.szPhoneNO = "12345678900";
    infoToUpdate.szEmail = "[email protected]";

    myContactBook.update( infoToUpdate );

    // Display POSONG's contact infomation to see if
    // it is successfully updated

    std::cout << "Display POSONG's contact information after updating it..." << std::endl;

    myContactBook.display( "POSONG" );

    std::cout << std::endl;

    //////////////////////////////////////////////////////////////////////////

    // Add someone else's contact information

    std::cout << "Adding RC's contact information..." << std::endl;

    ContactInfo infToAdd;
    infToAdd.nInstructorNO = 5;
    infToAdd.szName = "RC";
    infToAdd.szPhoneNO = "00987654321";
    infToAdd.szEmail = "[email protected]";

    myNewContactBook = myContactBook + infToAdd;

    // Display RC's contact infomation to see if
    // it is successfully updated

    std::cout << "Display RC's contact information after adding it..." << std::endl;

    myNewContactBook.display( "RC" );

    std::cout << std::endl;

    //////////////////////////////////////////////////////////////////////////

    // Display the contact book before saving it

    std::cout << "Display contact book before saving it..." << std::endl;

    myNewContactBook.display();

    std::cout << std::endl;

    // Save the contact book

    std::cout << "Save the contact book to file " 
	          << szOutputContactBookPath << "..." << std::endl;

    myNewContactBook.saveContactBook( szOutputContactBookPath );

    std::cin.get();

    return 0;
}
      ContactBook.h

#ifndef _CONTACT_BOOK_
#define _CONTACT_BOOK_

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

/**
* @brief Structure representing one's contact information
*/
typedef struct tagContactInfo
{
    // Instructor #
    int nInstructorNO;

    // Name
    std::string szName;

    // Phone Number
    std::string szPhoneNO;

    // Email
    std::string szEmail;

} ContactInfo;

/** >> operator overloading for stream input
* Read a contact infomation from some kind of stream.
*
* @param std::istream & IStream Some kind of input stream
* @param ContactInfo & info A piece of contact information
* @return std::istream & Just return the IStream object
* @see
* @note
*/
std::istream & operator>>( std::istream & IStream, ContactInfo & info );

/** >> operator overloading for stream output
* Output a contact infomation from some kind of stream.
*
* @param std::ostream & OStream Some kind of output stream
* @param ContactInfo & info A piece of contact information
* @return std::ostream & Just return the OStream object
* @see
* @note
*/
std::ostream & operator<<( std::ostream & OStream, ContactInfo & info );

class ContactBook
{
public:

    /** Constructor */
    ContactBook();

    /** Deconstructor */
    ~ContactBook();

    /** Copy constructor */
    ContactBook( const ContactBook & cttBook );

    /** Operator = (assigment) overloading */
    ContactBook & operator=( const ContactBook & cttBook );

public:

    /** Load contact book from file. 
    * Read the file with the specified name and
    * insert the contact infomation into the memory 
    * (i.e. the m_contactBook property of the class).
    *
    * @param const std::string & szContactFilePath File name of the contact book
    * @return bool Indicating whether the operation is successful
    * @see
    * @note
    */
    bool loadContactBook( const std::string & szContactFilePath );

    /** Save the contact book to file.
    * Save the contact book stored in the memory 
    * (i.e. the m_contactBook property of the class) to file.
    *
    * @param const std::string & szContactFilePath File name of the contact book
    * @return bool Indicating whether the operation is successful
    * @see
    * @note
    */
    bool saveContactBook( const std::string & szContactFilePath);

    /** Display all the contact book
    * Display all the contact infomation stored in the MEMORY.
    * Since we just display what is already loaded in the m_contactBook,
    * NO file reading operation is necessary.
    *
    * @param void
    * @return void
    * @see
    * @note
    */
    void displayAll( void );

    /** Display one's contact information
    * Display one's contact information stored in the MEMORY.
    * Since we just display what is already loaded in the m_contactBook,
    * NO file reading operation is necessary. If the name does not exist
    * in the contact book, please prompt it to us as well.
    *
    * @param const std::string & szName The name who we want to know the contact information
    * @return void
    * @see
    * @note
    */
    void displaySingle( const std::string & szName );

    /** Display the contact information
    * Display the contact information according to the
    * the presence of the name. If a name is given, then
    * display the contact infomation accosiate with it;
    * Otherwise display the whole contact book.
    *
    * @param const std::string & szName The name who we want to know the contact information
    * @return void
    * @see displaySingle displayAll
    * @note
    */
    void display( const std::string & szName = std::string() );

    /** Update one's contact information
    * Update one's contact information stored in the MEMORY.
    * Since we just update what is already loaded in the m_contactBook,
    * NO file reading or writing operation is required. If you want to
    * update file at the same time, just call the method 'saveContactBook'
    * in the main function after calling this method.
    *
    * @param const ContactInfo & contactInfo Contact infomation required to be updated
    * @return void
    * @see saveContactBook
    * @note
    */
    void update( const ContactInfo & contactInfo );

    /** Add one's contact information
    * Add one's contact information stored in the MEMORY.
    * Since we just add to what is already loaded in the m_contactBook,
    * NO file reading or writing operation is required. If you want to
    * update file at the same time, just call the method 'saveContactBook'
    * in the main function after calling this method.
    *
    * @param const ContactInfo & contactInfo Contact infomation required to be added
    * @return void
    * @see saveContactBook
    * @note
    */
    void add( const ContactInfo & contactInfo );

    /** Member operator+ overloading
    * Add the original contact book and the new contact information and 
    * create a new contact book to store the result.
    *
    * @param const ContactInfo & contactInfo Contact infomation required to be added
    * @return const ContactBook The contact book after adding the new contact information
    * @see
    * @note You can implement ONLY ONE of the member and non-member operator+ function
    */
    const ContactBook operator+( const ContactInfo & contactInfo ) const;

    /** Non-member operator+ overloading, uncomment the following if you want to implement it */
    // friend const ContactBook operator+( const ContactBook & cttBook, const ContactInfo & contactInfo );

private:

    /** Property for contact book storage.
    * The 'm_' prefix means that the variable is 
    * a member variable of the class. And it's just
    * a name so don't be afraid of it.
    */
    std::vector<ContactInfo> m_contactBook;
};

/** Non-member operator+ overloading
* Add the original contact book and the new contact information and 
* create a new contact book to store the result.
*
* @param const ContactBook & cttBook The original contact book
* @param const ContactInfo & contactInfo Contact infomation required to be added
* @return const ContactBook The contact book after adding the new contact information
* @see
* @note You can implement ONLY ONE of the member and non-member operator+ function
*/
/** Non-member operator+ overloading, uncomment the following if you want to implement it */
// const ContactBook operator+( const ContactBook & cttBook, const ContactInfo & contactInfo );

#endif
      ContactBook.cpp

#include "ContactBook.h"

std::istream & operator>>( std::istream & IStream, ContactInfo & info )
{
    /** WRITE YOUR CODE HERE */
    IStream >> info.nInstructorNO;
    IStream >> info.szName;
    IStream >> info.szPhoneNO;
    IStream >> info.szEmail;

    return IStream;
}

std::ostream & operator<<( std::ostream & OStream, ContactInfo & info )
{
    /** WRITE YOUR CODE HERE */
    OStream << info.nInstructorNO << " ";
    OStream << info.szName << " ";
    OStream << info.szPhoneNO << " ";
    OStream << info.szEmail;

    return OStream;
}

ContactBook::ContactBook()
{
    std::cout << "Constructor of the class \'ContactBook\'." << std::endl;
}

ContactBook::ContactBook( const ContactBook & cttBook )
{
    std::cout << "Copy Constructor of the class \'ContactBook\'." << std::endl;

    /** WRITE YOUR CODE HERE */
    if ( this != &cttBook )
    {
        this->m_contactBook = cttBook.m_contactBook;
    }
}

ContactBook & ContactBook::operator=( const ContactBook & cttBook )
{
    /** WRITE YOUR CODE HERE */
    if ( this != &cttBook )
    {
        this->m_contactBook = cttBook.m_contactBook;
    }

    return (*this);
}

ContactBook::~ContactBook()
{
    std::cout << "Deconstructor of the class \'ContactBook\'." << std::endl;
}

/** Load contact book from file. 
* Read the file with the specified name and
* insert the contact infomation into the memory 
* (i.e. the m_contactBook property of the class).
*
* @param const std::string & szContactFilePath File name of the contact book
* @return bool Indicating whether the operation is successful
* @see
* @note
*/
bool ContactBook::loadContactBook( const std::string & szContactFilePath )
{
    std::ifstream inFile( szContactFilePath );

    if ( !inFile.is_open() )
    {
        return false;
    }

    m_contactBook.clear();

    ContactInfo info;

    while ( true )
    {
        bool bSuccessful = false;
        bSuccessful = inFile >> info;

        if ( !bSuccessful )
        {
            break;
        }

        m_contactBook.push_back( info );
    }

    inFile.close();

    return true;
}

/** Save the contact book to file.
* Save the contact book stored in the memory 
* (i.e. the m_contactBook property of the class) to file.
*
* @param const std::string & szContactFilePath File name of the contact book
* @return bool
* @see
* @note
*/
bool ContactBook::saveContactBook( const std::string & szContactFilePath )
{
    std::ofstream outFile( szContactFilePath );

    if ( !outFile.is_open() )
    {
        return false;
    }

    for ( int i = 0; i < m_contactBook.size(); i++ )
    {
        outFile << m_contactBook[i] << std::endl;
    }

    outFile.close();

    return true;
}

/** Display all the contact book
* Display all the contact infomation stored in the MEMORY.
* Since we just display what is already loaded in the m_contactBook,
* NO file reading operation is necessary.
*
* @param void
* @return void
* @see
* @note
*/
void ContactBook::displayAll( void )
{
    if ( m_contactBook.empty() )
    {
        std::cout << "There is no information stored in the contact book." << std::endl;
        return;
    }

    for ( int i = 0; i < m_contactBook.size(); i++ )
    {
        std::cout << m_contactBook[i] << std::endl;
    }
}

/** Display one's contact information
* Display one's contact information stored in the MEMORY.
* Since we just display what is already loaded in the m_contactBook,
* NO file reading operation is necessary. If the name does not exist
* in the contact book, please prompt it to us as well.
*
* @param const std::string & szName The name who we want to know the contact information
* @return void
* @see
* @note
*/
void ContactBook::displaySingle( const std::string & szName )
{
    bool bFound = false;

    for ( int i = 0; i < m_contactBook.size(); i++ )
    {
        if ( szName == m_contactBook[i].szName )
        {
            std::cout << m_contactBook[i] << std::endl;

            bFound = true;

            break;
        }
    }

    if ( !bFound )
    {
        std::cout << "There is no contact information associated with name " << szName << "." << std::endl;
    }
}

void ContactBook::display( const std::string & szName /*= std::string() */ )
{
    /** WRITE YOUR CODE HERE */
    if ( szName.empty() )
    {
        displayAll();
    }
    else
    {
        displaySingle( szName );
    }
}

/** Update one's contact information
* Update one's contact information stored in the MEMORY.
* Since we just update what is already loaded in the m_contactBook,
* NO file reading or writing operation is required. If you want to
* update file at the same time, just call the method 'saveContactBook'
* in the main function after calling this method.
*
* @param const ContactInfo & contactInfo Contact infomation required to be updated
* @return void
* @see saveContactBook
* @note
*/
void ContactBook::update( const ContactInfo & contactInfo )
{
    bool bFound = false;

    for ( int i = 0; i < m_contactBook.size(); i++ )
    {
        if ( contactInfo.szName == m_contactBook[i].szName )
        {
            m_contactBook[i] = contactInfo;

            bFound = true;

            break;
        }
    }

    if ( !bFound )
    {
        std::cout << "There is no contact information associated with name " << contactInfo.szName << "." << std::endl;
    }
}

/** Add one's contact information
* Add one's contact information stored in the MEMORY.
* Since we just add to what is already loaded in the m_contactBook,
* NO file reading or writing operation is required. If you want to
* update file at the same time, just call the method 'saveContactBook'
* in the main function after calling this method.
*
* @param const ContactInfo & contactInfo Contact infomation required to be added
* @return void
* @see saveContactBook
* @note
*/
void ContactBook::add( const ContactInfo & contactInfo )
{
    m_contactBook.push_back( contactInfo );
}

const ContactBook ContactBook::operator+( const ContactInfo & contactInfo ) const
{
    /** WRITE YOUR CODE HERE */
    ContactBook newContactBook;
    newContactBook = (*this);
    newContactBook.m_contactBook.push_back( contactInfo );

    return newContactBook;
}

/** Non-member operator+ overloading, uncomment the following if you want to implement it */
//const ContactBook operator+( const ContactBook & cttBook, const ContactInfo & contactInfo )
//{
//    ContactBook newContactBook;
//    newContactBook = cttBook;
//    newContactBook.m_contactBook.push_back( contactInfo );
//
//    return newContactBook;
//}

      基于上述实现程序的输出

Constructor of the class 'ContactBook'.
Constructor of the class 'ContactBook'.
Load contact book from file ./Contact.txt...

Display contact book...
1 GUOHONGYUN 15XXXXXXXXX [email protected]
1 LICHAO 15XXXXXXXXX [email protected]
1 XIAYUZHE 15XXXXXXXXX [email protected]
1 POSONG 13XXXXXXXXX [email protected]
1 LIUBO 15XXXXXXXXX [email protected]
1 LEIYU 18XXXXXXXXX [email protected]
1 ZHANGCANGJU 13XXXXXXXXX [email protected]
1 XIANGKAILIN 18XXXXXXXXX [email protected]
2 HUANGHAO 15XXXXXXXXX [email protected]
2 ZHUJIAJUN 15XXXXXXXXX [email protected]
2 ZHONGCHENG 13XXXXXXXXX [email protected]
3 LEIJUNAN 13XXXXXXXXX [email protected]
3 YANGBO 15XXXXXXXXX [email protected]
4 WEIWEI 15XXXXXXXXX [email protected]
4 LIUTINGWEI 15XXXXXXXXX [email protected]
4 OUYANGYU 15XXXXXXXXX [email protected]
5 ZHANGXINHAO 15XXXXXXXXX [email protected]
5 HOUTINGWU 15XXXXXXXXX [email protected]
6 KONGQIAO 13XXXXXXXXX [email protected]
6 SIXU 13XXXXXXXXX [email protected]
6 ZHANGJINJING 18XXXXXXXXX [email protected]
7 YANJUNHUA 13XXXXXXXXX [email protected]
7 HUANGRUI 13XXXXXXXXX [email protected]

Display POSONG's contact information...
1 POSONG 13XXXXXXXXX [email protected]

Update POSONG's contact information...
Display POSONG's contact information after updating it...
1 POSONG 12345678900 [email protected]

Adding RC's contact information...
Constructor of the class 'ContactBook'.
Copy Constructor of the class 'ContactBook'.
Deconstructor of the class 'ContactBook'.
Deconstructor of the class 'ContactBook'.
Display RC's contact information after adding it...
5 RC 00987654321 [email protected]

Display contact book before saving it...
1 GUOHONGYUN 15XXXXXXXXX [email protected]
1 LICHAO 15XXXXXXXXX [email protected]
1 XIAYUZHE 15XXXXXXXXX [email protected]
1 POSONG 12345678900 [email protected]
1 LIUBO 15XXXXXXXXX [email protected]
1 LEIYU 18XXXXXXXXX [email protected]
1 ZHANGCANGJU 13XXXXXXXXX [email protected]
1 XIANGKAILIN 18XXXXXXXXX [email protected]
2 HUANGHAO 15XXXXXXXXX [email protected]
2 ZHUJIAJUN 15XXXXXXXXX [email protected]
2 ZHONGCHENG 13XXXXXXXXX [email protected]
3 LEIJUNAN 13XXXXXXXXX [email protected]
3 YANGBO 15XXXXXXXXX [email protected]
4 WEIWEI 15XXXXXXXXX [email protected]
4 LIUTINGWEI 15XXXXXXXXX [email protected]
4 OUYANGYU 15XXXXXXXXX [email protected]
5 ZHANGXINHAO 15XXXXXXXXX [email protected]
5 HOUTINGWU 15XXXXXXXXX [email protected]
6 KONGQIAO 13XXXXXXXXX [email protected]
6 SIXU 13XXXXXXXXX [email protected]
6 ZHANGJINJING 18XXXXXXXXX [email protected]
7 YANJUNHUA 13XXXXXXXXX [email protected]
7 HUANGRUI 13XXXXXXXXX [email protected]
5 RC 00987654321 [email protected]

Save the contact book to file ./ContactModified.txt...
Deconstructor of the class 'ContactBook'.
Deconstructor of the class 'ContactBook'.

你可能感兴趣的:(【CPPTraining】Techniques towards Less Coding PA)