<<C++Primer PLus 第五版>>读书笔记3

包含对象成员的类
valarray类是由头文件valarray支持的。顾名思义,这个类用于处理数值,他支持诸如将数组中的所有元素的值想家以及在数组中找出最大和最小的值等操作。valarray被定义为一个模板类,以便能够处理不同的数据类型。

一个Student类----一个getline导致构造函数递归的类

  1. // readBook2.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "valarray"  
  8. #include "string"  
  9.   
  10. class CStudent  
  11. {  
  12. public:  
  13.     typedef std::valarray<double> ArrayDb;  
  14.     CStudent() : sz_Name( "Null Student" ), m_ArrScores()  
  15.     {  
  16.     }  
  17.     CStudent( const string& name ) : sz_Name( name ), m_ArrScores()  
  18.     {  
  19.     }  
  20.     explicit CStudent( int n  ) : sz_Name( "Nully" ), m_ArrScores( n )  
  21.     {  
  22.     }  
  23.     CStudent( const string& name, int n ) : sz_Name( name ), m_ArrScores( n )  
  24.     {  
  25.     }  
  26.     CStudent( const string& name, const ArrayDb& a ) : sz_Name( name ), m_ArrScores( a )  
  27.     {  
  28.     }  
  29.     CStudent( const char* name, const double* pd, int n ) : sz_Name( name ), m_ArrScores( pd, n )  
  30.     {  
  31.     }  
  32.     double Average() const  
  33.     {  
  34.         if ( m_ArrScores.size() > 0 )  
  35.         {  
  36.             return ( m_ArrScores.sum() / m_ArrScores.size() );  
  37.         }  
  38.         else  
  39.         {  
  40.             return 0;  
  41.         }  
  42.     }  
  43.     const string& GetName() const  
  44.     {  
  45.         return sz_Name;  
  46.     }  
  47.     double& operator[]( int i)  
  48.     {  
  49.         return m_ArrScores[ i ];  
  50.     }  
  51.     double operator[]( int i ) const  
  52.     {  
  53.         return m_ArrScores[ i ];  
  54.     }  
  55.     ostream& CStudent::arr_out( ostream& os ) const  
  56.     {  
  57.         int i;  
  58.         int lim = m_ArrScores.size();  
  59.         if ( lim > 0 )  
  60.         {  
  61.             for ( i = 0; i < lim; i++ )  
  62.             {  
  63.                 os << m_ArrScores[ i ] << "   ";  
  64.                 if ( 4 == i % 5 )  
  65.                 {  
  66.                     os << endl;  
  67.                 }  
  68.             }  
  69.             if ( 0 != i % 5 )  
  70.             {  
  71.                 os << endl;  
  72.             }  
  73.         }  
  74.         else  
  75.         {  
  76.             os << "empty array";  
  77.         }  
  78.         return os;  
  79.     }  
  80.     friend istream& operator >>( istream& is, CStudent& stu );  
  81.     friend istream& operator <<( istream& os, const CStudent& stu );  
  82.     friend istream& getline( istream& is, const CStudent& stu );  
  83.     ~CStudent(){};  
  84. private:  
  85.     string sz_Name;  
  86.     ArrayDb m_ArrScores;  
  87. };  
  88.   
  89. istream& operator >>( istream& is, CStudent& stu )  
  90. {  
  91.     is >> stu.sz_Name;  
  92.     return is;  
  93. }  
  94.   
  95. ostream& operator <<( ostream& os, const CStudent& stu )  
  96. {  
  97.     os << "this student name is:" << stu.GetName() << endl;  
  98.     os << "this student scores is:" << endl;  
  99.     stu.arr_out( os );  
  100.     return os;  
  101. }  
  102. istream& getline( istream& is, const CStudent& stu )  
  103. {  
  104.     getline( is, stu.sz_Name );  
  105.     return is;  
  106. }  
  107.   
  108. const int puplis = 3;  
  109. const int quizzes = 5;  
  110. void set( CStudent& sa, int n );  
  111.   
  112. int _tmain(int argc, _TCHAR* argv[])  
  113. {  
  114.     CStudent ada[ puplis ] = { CStudent( quizzes ), CStudent( quizzes ), CStudent( quizzes ) };  
  115.     int i;  
  116.     for ( i = 0; i < puplis; ++i )  
  117.     {  
  118.         set( ada[ i ], quizzes );  
  119.     }  
  120.     cout << "\nStudent List:" << endl;  
  121.     for ( i = 0; i < puplis; ++i )  
  122.     {  
  123.         cout << ada[ i ].GetName() << endl;  
  124.     }  
  125.     cout << "\nResults:" << endl;  
  126.     for ( i = 0; i < puplis; i++ )  
  127.     {  
  128.         cout << endl << ada[ i ];  
  129.         cout << "average" << ada[ i ].Average() << endl;  
  130.     }  
  131.     cout << "Done." << endl;  
  132.   
  133.     return 0;  
  134. }  
  135.   
  136. void set( CStudent& sa, int n )  
  137. {  
  138.     cout << "Please enter the student name:" << endl;  
  139.     getline( cin, sa );  
  140.     cout << "Please enter " << n << "quiz scores:" << endl;  
  141.     for ( int i = 0; i < n; i++ )  
  142.     {  
  143.         cin >> sa[ i ];  
  144.     }  
  145.     while'\n' != cin.get() )  
  146.     {  
  147.         continue;  
  148.     }  
  149. }  

// 在
istream& getline( istream& is, const CStudent& stu )
{
    getline( is, stu.sz_Name );
    return is;
}
//const CStudent& stu导致递归

修改之后的版本

  1. // readBook2.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "valarray"  
  8. #include "string"  
  9.   
  10. class CStudent  
  11. {  
  12. public:  
  13.     typedef std::valarray<double> ArrayDb;  
  14.     CStudent() : sz_Name( "Null Student" ), m_ArrScores()  
  15.     {  
  16.     }  
  17.     CStudent( const string& name ) : sz_Name( name ), m_ArrScores()  
  18.     {  
  19.     }  
  20.     explicit CStudent( int n  ) : sz_Name( "Nully" ), m_ArrScores( n )  
  21.     {  
  22.     }  
  23.     CStudent( const string& name, int n ) : sz_Name( name ), m_ArrScores( n )  
  24.     {  
  25.     }  
  26.     CStudent( const string& name, const ArrayDb& a ) : sz_Name( name ), m_ArrScores( a )  
  27.     {  
  28.     }  
  29.     CStudent( const char* name, const double* pd, int n ) : sz_Name( name ), m_ArrScores( pd, n )  
  30.     {  
  31.     }  
  32.     double Average() const  
  33.     {  
  34.         if ( m_ArrScores.size() > 0 )  
  35.         {  
  36.             return ( m_ArrScores.sum() / m_ArrScores.size() );  
  37.         }  
  38.         else  
  39.         {  
  40.             return 0;  
  41.         }  
  42.     }  
  43.     const string& GetName() const  
  44.     {  
  45.         return sz_Name;  
  46.     }  
  47.     double& operator[]( int i)  
  48.     {  
  49.         return m_ArrScores[ i ];  
  50.     }  
  51.     double operator[]( int i ) const  
  52.     {  
  53.         return m_ArrScores[ i ];  
  54.     }  
  55.     ostream& CStudent::arr_out( ostream& os ) const  
  56.     {  
  57.         int i;  
  58.         int lim = m_ArrScores.size();  
  59.         if ( lim > 0 )  
  60.         {  
  61.             for ( i = 0; i < lim; i++ )  
  62.             {  
  63.                 os << m_ArrScores[ i ] << "   ";  
  64.                 if ( 4 == i % 5 )  
  65.                 {  
  66.                     os << endl;  
  67.                 }  
  68.             }  
  69.             if ( 0 != i % 5 )  
  70.             {  
  71.                 os << endl;  
  72.             }  
  73.         }  
  74.         else  
  75.         {  
  76.             os << "empty array";  
  77.         }  
  78.         return os;  
  79.     }  
  80.     friend istream& operator >>( istream& is, CStudent& stu );  
  81.     friend istream& operator <<( istream& os, const CStudent& stu );  
  82.     friend istream& getline( istream& is, CStudent& stu );  
  83.     ~CStudent(){};  
  84. private:  
  85.     string sz_Name;  
  86.     ArrayDb m_ArrScores;  
  87. };  
  88.   
  89. istream& operator >>( istream& is, CStudent& stu )  
  90. {  
  91.     is >> stu.sz_Name;  
  92.     return is;  
  93. }  
  94.   
  95. ostream& operator <<( ostream& os, const CStudent& stu )  
  96. {  
  97.     os << "this student name is:" << stu.GetName() << endl;  
  98.     os << "this student scores is:" << endl;  
  99.     stu.arr_out( os );  
  100.     return os;  
  101. }  
  102. istream& getline( istream& is, CStudent& stu )  
  103. {  
  104.     getline( is, stu.sz_Name );  
  105.     return is;  
  106. }  
  107.   
  108. const int puplis = 3;  
  109. const int quizzes = 5;  
  110. void set( CStudent& sa, int n );  
  111.   
  112. int _tmain(int argc, _TCHAR* argv[])  
  113. {  
  114.     CStudent ada[ puplis ] = { CStudent( quizzes ), CStudent( quizzes ), CStudent( quizzes ) };  
  115.     int i;  
  116.     for ( i = 0; i < puplis; ++i )  
  117.     {  
  118.         set( ada[ i ], quizzes );  
  119.     }  
  120.     cout << "\nStudent List:" << endl;  
  121.     for ( i = 0; i < puplis; ++i )  
  122.     {  
  123.         cout << ada[ i ].GetName() << endl;  
  124.     }  
  125.     cout << "\nResults:" << endl;  
  126.     for ( i = 0; i < puplis; i++ )  
  127.     {  
  128.         cout << endl << ada[ i ];  
  129.         cout << "average" << ada[ i ].Average() << endl;  
  130.     }  
  131.     cout << "Done." << endl;  
  132.   
  133.     return 0;  
  134. }  
  135.   
  136. void set( CStudent& sa, int n )  
  137. {  
  138.     cout << "Please enter the student name:";  
  139.     getline( cin, sa );  
  140.     cout << "Please enter " << n << "quiz scores:" << endl;  
  141.     for ( int i = 0; i < n; i++ )  
  142.     {  
  143.         cin >> sa[ i ];  
  144.     }  
  145.     while'\n' != cin.get() )  
  146.     {  
  147.         continue;  
  148.     }  
  149. }  


私有继承
    c++还有另一种实现has-a关系的途径----私有继承。使用私有继承,基类的公有成员和保护成员都将成为派生类的私有成员。这意味着基类方法将不会成为派生对象公有接口的一部分,但可以在派生类的成员函数中使用它们。
    使用公有继承,基类的公有方法将成为派生类的公有方法。简而言之,派生类将继承基类的接口,这是is-a关系的一部分。使用私有继承,基类的公有方法将成为派生类的私有方法。简而言之,派生类不能继承基类的接口。正如从被包含对象中看到的,这种不完全继承是has-a关系的一部分。
    因此私有继承提供的特性与包含相同:获得实现,但不获得接口。所以,私有继承也可以用来实现has-a关系。

  1. #include "stdafx.h"  
  2. #include "iostream"  
  3. using namespace std;  
  4. #include "valarray"  
  5. #include "string"  
  6.   
  7. class CStudent : private valarray<double>, private string  
  8. {  
  9. private:  
  10.     typedef std::valarray<double> ArrayDb;  
  11. public:  
  12.     CStudent() : string( "Null Student" ), ArrayDb()  
  13.     {  
  14.     }  
  15.     CStudent( const string& name ) : string( name ), ArrayDb()  
  16.     {  
  17.     }  
  18.     explicit CStudent( int n  ) : string( "Nully" ), ArrayDb( n )  
  19.     {  
  20.     }  
  21.     CStudent( const string& name, int n ) : string( name ), ArrayDb( n )  
  22.     {  
  23.     }  
  24.     CStudent( const string& name, const ArrayDb& a ) : string( name ), ArrayDb( a )  
  25.     {  
  26.     }  
  27.     CStudent( const char* name, const double* pd, int n ) : string( name ), ArrayDb( pd, n )  
  28.     {  
  29.     }  
  30.     ~CStudent(){};  
  31.     double Average() const  
  32.     {  
  33.         if ( ArrayDb::size() > 0 )  
  34.         {  
  35.             return ( ArrayDb::sum() / ArrayDb::size() );  
  36.         }  
  37.         else  
  38.         {  
  39.             return 0;  
  40.         }  
  41.     }  
  42.     const string& GetName() const  
  43.     {  
  44.         return ( const string& ) *this;  
  45.     }  
  46.     double& operator[] ( int i )  
  47.     {  
  48.         return ArrayDb::operator[]( i );  
  49.     }  
  50.     const double operator[] ( int i ) const  
  51.     {  
  52.         return ArrayDb::operator[]( i );  
  53.     }  
  54.     ostream& arr_out( ostream& os ) const  
  55.     {  
  56.         int i;  
  57.         int lim = ArrayDb::size();  
  58.         if ( lim > 0 )  
  59.         {  
  60.             for ( i = 0; i < lim; i++ )  
  61.             {  
  62.             //  os << ArrayDb[ i ] << "   ";  
  63.                 os << ArrayDb::operator[]( i ) << "    ";  
  64.                 if ( 4 == i % 5 )  
  65.                 {  
  66.                     os << endl;  
  67.                 }  
  68.             }  
  69.             if ( 0 != i % 5 )  
  70.             {  
  71.                 os << endl;  
  72.             }  
  73.         }  
  74.         else  
  75.         {  
  76.             os << "empty array";  
  77.         }  
  78.         return os;  
  79.     }  
  80.     friend istream& operator >>( istream& is, CStudent& stu );  
  81.     friend istream& operator <<( istream& os, const CStudent& stu );  
  82.     friend istream& getline( istream& is, CStudent& stu );  
  83. };  
  84.   
  85. istream& operator >>( istream& is, CStudent& stu )  
  86. {  
  87.     is >> ( string& )stu;  
  88.     return is;  
  89. }  
  90.   
  91. ostream& operator <<( ostream& os, const CStudent& stu )  
  92. {  
  93.     os << "this student name is:" << stu.GetName() << endl;  
  94.     os << "this student scores is:" << endl;  
  95.     stu.arr_out( os );  
  96.     return os;  
  97. }  
  98. istream& getline( istream& is, CStudent& stu )  
  99. {  
  100.     getline( is, ( string& )stu );  
  101.     return is;  
  102. }  
  103.   
  104. const int puplis = 3;  
  105. const int quizzes = 5;  
  106. void set( CStudent& sa, int n );  
  107.   
  108. int _tmain(int argc, _TCHAR* argv[])  
  109. {  
  110.     CStudent ada[ puplis ] = { CStudent( quizzes ), CStudent( quizzes ), CStudent( quizzes ) };  
  111.     int i;  
  112.     for ( i = 0; i < puplis; ++i )  
  113.     {  
  114.         set( ada[ i ], quizzes );  
  115.     }  
  116.     cout << "\nStudent List:" << endl;  
  117.     for ( i = 0; i < puplis; ++i )  
  118.     {  
  119.         cout << ada[ i ].GetName() << endl;  
  120.     }  
  121.     cout << "\nResults:" << endl;  
  122.     for ( i = 0; i < puplis; i++ )  
  123.     {  
  124.         cout << endl << ada[ i ];  
  125.         cout << "average" << ada[ i ].Average() << endl;  
  126.     }  
  127.     cout << "Done." << endl;  
  128.   
  129.     return 0;  
  130. }  
  131.   
  132. void set( CStudent& sa, int n )  
  133. {  
  134.     cout << "Please enter the student name:";  
  135.     getline( cin, sa );  
  136.     cout << "Please enter " << n << "quiz scores:" << endl;  
  137.     for ( int i = 0; i < n; i++ )  
  138.     {  
  139.         cin >> sa[ i ];  
  140.     }  
  141.     while'\n' != cin.get() )  
  142.     {  
  143.         continue;   }  
  144. }  

在CStudent类中,使用作用域解析操作符可以访问基类的方法,但要使用基类对象本身,比如调用GetName()方法,他返回string对象成员name,但使用私有继承时,该string对象没有名称,只能使用强制类型转换。由于CStudent类是从string派生出来的,因此可以用过强制类型转换,将CStudent对象转换为string对象,结果为继承而来的string对象。
  1. const string& GetName() const  
  2. {  
  3.     return ( const string& ) *this;  
  4. }  


引用stu不会自动转换为string引用,根本原因在于,在私有继承中,不在进行显示类型转换的清华下,不能讲指向派生类的引用或指针赋给基类引用或指针。不过,即使这个例子使用的是公有继承,也必须使用显示类型转换。原因之一是,如果不适用类型转换,代码is >>stu;与友元函数原型匹配,从而导致递归调用:

  1. istream& operator >>( istream& is, CStudent& stu )  
  2. {  
  3.     is >> ( string& )stu;  
  4.     return is;  
  5. }  


 

另一个原因是,由于这个类使用的是多重继承,编译器将无法确定应转换成哪个基类,如果两个基类都提供了函数operator<<()。

 

使用包含还是私有继承
    由于既可以使用包含,也可以使用私有继承来建立has-a关系。大多数c++程序员倾向于前者。不过私有继承所提供的特性确实比包含多。例如,假设类包含保护成员,则这样的成员在派生类中式可用的,但在继承层次机构外是不可用的。如果使用组合奖这样的类保护在另一类中,则后者将不是排成类,而是位于继承层次结构之外,因此不能访问保护成员。但通过继承的到的将是派生类,因此他能够访问保护成员。
    另一种需要使用私有继承的情况是需要重新定义虚函数。派生类可以重新定义虚函数,但包含类不能。使用私有继承,重新定义的函数将只能在类中使用,而不是公有的。

 

多重继承(MI)
    为了解决多重继承而引入虚基类,也就是继承的两个类都含有相同函数的时候,产生无法识别该函数,引入了虚基类,只需要在调用某个父类的方法的时候,加上类名限定符即可
一个例子(注意这里为了能够进行显示转换需要使用virtual public方式继承)

  1. // testMI.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9. class Worker  
  10. {  
  11. public:  
  12.     Worker( const string& Name, long Id ) : m_fullName( Name ), m_lId( Id )  
  13.     {  
  14.     }  
  15.     Worker() : m_fullName( "no one" ), m_lId( 0L )  
  16.     {  
  17.     }  
  18.     virtual ~Worker() = 0;  
  19.     virtual void Set() = 0;  
  20.     virtual void Show() const = 0;  
  21. protected:  
  22.     void Data() const  
  23.     {  
  24.         cout << "Name:" << m_fullName << endl;  
  25.         cout << "Employee ID:" << m_lId << endl;  
  26.     }  
  27.     void Get()  
  28.     {  
  29.         getline( cin, m_fullName );  
  30.         cout << "Enter worker's ID:";  
  31.         cin >> m_lId;  
  32.         while ( '\n' != cin.get() )  
  33.         {  
  34.             continue;  
  35.         }  
  36.     }  
  37. private:  
  38.     string m_fullName;  
  39.     long m_lId;  
  40. };  
  41. Worker::~Worker()  
  42. {  
  43. }  
  44.   
  45. class Waiter : virtual public Worker  
  46. {  
  47. public:  
  48.     Waiter() : Worker(), m_nPanache( 0 )  
  49.     {  
  50.     }  
  51.     Waiter( const string& Name, long Id, int p = 0 ) : Worker( Name, Id ), m_nPanache( p )  
  52.     {  
  53.     }  
  54.     Waiter( const Worker& rWorker, int p = 0 ) : Worker( rWorker ), m_nPanache( p )  
  55.     {  
  56.     }  
  57.     void Set()  
  58.     {  
  59.         cout << "Enter waiter's name:";  
  60.         Worker::Get();  
  61.         Get();  
  62.     }  
  63.     void Show() const  
  64.     {  
  65.         cout << "Category:waiter" << endl;  
  66.         Worker::Data();  
  67.         Data();  
  68.     }  
  69. protected:  
  70.     void Data() const  
  71.     {  
  72.         cout << "Panache rating:" << m_nPanache << endl;  
  73.     }  
  74.     void Get()  
  75.     {  
  76.         cout << "Enter waiter's Panache rating:";  
  77.         cin >> m_nPanache;  
  78.         while ( '\n' != cin.get() )  
  79.         {  
  80.             continue;  
  81.         }  
  82.     }  
  83. private:  
  84.     int m_nPanache;  
  85. };  
  86.   
  87. class Singer : virtual public Worker  
  88. {  
  89. public:  
  90.     Singer() : Worker(), voice( 0 )  
  91.     {  
  92.     }  
  93.     Singer( const string& Name, long Id, int v = 0 ) : Worker( Name, Id ), voice( v )  
  94.     {  
  95.     }  
  96.     Singer( const Worker& rWorker, int v = 0 ) : Worker( rWorker ), voice( v )  
  97.     {  
  98.     }  
  99.     void Set()  
  100.     {  
  101.         cout << "Enter singer's name:";  
  102.         Worker::Get();  
  103.         Get();  
  104.     }  
  105.     void Show() const  
  106.     {  
  107.         cout << "Category:singer" << endl;  
  108.         Worker::Data();  
  109.         Data();  
  110.     }  
  111. protected:  
  112.     enum{ other, alto, contralto, soprano, base, baritone, tenor };  
  113.     enum{ Vtypes = 7 };  
  114.     void Data() const  
  115.     {  
  116.         cout << "Vocal range:" << pv[ voice ] << endl;  
  117.     }  
  118.     void Get()  
  119.     {  
  120.         cout << "Enter number for singer's vocal range:" << endl;  
  121.         int i;  
  122.         for ( i = 0; i < Vtypes; i++ )  
  123.         {  
  124.             cout << i << ":" << pv[ i ] << "    ";  
  125.             if ( 3 == i % 4 )  
  126.             {  
  127.                 cout << endl;  
  128.             }  
  129.         }  
  130.         if ( 0 != i % 4 )  
  131.         {  
  132.             cout << endl;  
  133.         }  
  134.         cin >> voice;  
  135.         while ( '\n' != cin.get() )  
  136.         {  
  137.             continue;  
  138.         }  
  139.     }  
  140. private:  
  141.     static char* pv[ Vtypes ];  
  142.     int voice;  
  143. };  
  144.   
  145. char* Singer::pv[ Singer::Vtypes ] = { "other""alto""contralto""Soprano""bass""baritone""tenor" };  
  146.   
  147. class SingingWaiter : public Singer, public Waiter  
  148. {  
  149. public:  
  150.     SingingWaiter(){}  
  151.     SingingWaiter( const string& Name, long Id, int p = 0, int v = other )  
  152.         :  Worker( Name, Id ), Waiter( Name, Id, p ), Singer( Name, Id, v )  
  153.     {  
  154.     }  
  155.     SingingWaiter( const Worker& rWorker, int p = 0, int v = other )  
  156.         :  Worker( rWorker ), Waiter( rWorker, p ), Singer( rWorker, v )  
  157.     {  
  158.     }  
  159.     SingingWaiter( const Waiter& rWaiter, int v = other )  
  160.         :  Worker( rWaiter ), Waiter( rWaiter ), Singer( rWaiter, v )  
  161.     {  
  162.     }  
  163.     SingingWaiter( const Singer& rSinger, int p = 0 )  
  164.         :  Worker( rSinger ), Waiter( rSinger, p ), Singer( rSinger )  
  165.     {  
  166.     }  
  167.     void Set()  
  168.     {  
  169.         cout << "Enter singing waiter's name:";  
  170.         Worker::Get();  
  171.         Get();  
  172.     }  
  173.     void Show() const  
  174.     {  
  175.         cout << "Category:singing waiter" << endl;  
  176.         Worker::Data();  
  177.         Data();  
  178.     }  
  179. protected:  
  180.     void Data() const  
  181.     {  
  182.         Singer::Data();  
  183.         Waiter::Data();  
  184.     }  
  185.     void Get()  
  186.     {  
  187.         Waiter::Get();  
  188.         Singer::Get();  
  189.     }  
  190. };  
  191.   
  192. const int SIZE = 5;  
  193.   
  194. int _tmain(int argc, _TCHAR* argv[])  
  195. {  
  196.     Worker* loals[ SIZE ];  
  197.     int ct;  
  198.     for ( ct = 0; ct < SIZE; ct++ )  
  199.     {  
  200.         char choice;  
  201.         cout << "Enter the employee category:" << endl;  
  202.         cout << "w:waiter s:singer    " << "t:sing waiter q:quit" << endl;  
  203.         cin >> choice;  
  204.   
  205.         while ( NULL == strchr( "wstq", choice ) )  
  206.         {  
  207.             cout << "Please enter a, w, s, t, or, q:";  
  208.             cin >> choice;  
  209.         }  
  210.         if ( 'q' == choice )  
  211.         {  
  212.             break;  
  213.         }  
  214.         switch ( choice )  
  215.         {  
  216.         case 'w':  
  217.             loals[ ct ] = new Waiter; break;  
  218.         case 's':  
  219.             loals[ ct ] = new Singer; break;  
  220.         case 't':  
  221.             loals[ ct ] = new SingingWaiter; break;  
  222.         }  
  223.         cin.get();  
  224.         loals[ ct ]->Set();  
  225.     }  
  226.     cout << "\nHere is your staff:" << endl;  
  227.     int i;  
  228.     for ( i = 0; i < ct; i++ )  
  229.     {  
  230.         cout << endl;  
  231.         loals[ i ]->Show();  
  232.     }  
  233.     for ( i = 0; i < ct; i++ )  
  234.     {  
  235.         delete loals[ i ];  
  236.     }  
  237.     cout << "Done." << endl;  
  238.   
  239.   
  240.   
  241.     return 0;  
  242. }  


 

类模板
    模板的声明template<typename Type>,关键字typename告诉编译器,将要定义一个模板。尖括号中的内容相当于函数的参数列表。可以把关键字typename看作是变量的类型名,该变量接受类型作为其值,把Type看做是该变量的名称。
    类模板里面的成员函数,每个函数头都将以相同的模板声明打头
    除非编译器实现了新的export关键字,否则将模板成员函数放置在一个独立的实现文件中将无法运行。因为模板不是函数,它们不能单独编译。模板必须与特定的模板实例化请求一起使用。为此,最简单的方法是将所有模板信息放在一个头文件中,并在要使用这些模板的文件中包含该头文件。

 

深入探讨模板类
    使用指针堆栈的方法之一是,让调用程序提供一个指针数组,其中每个指针都指向不同的字符串。把这些指针放在堆栈中是有意义的,因为每个指针都将指向不同的字符串。注意,创建不同指针时调用程序的职责,而不是堆栈的职责。堆栈的任务是管理指针,而不是创建指针。
    例如,假设要模拟下面的情况。某人将一车文件夹交付给了Plodson。如果Plodson的收取篮(in-basket)是空的,他将取出车中最上面的文件夹,将其放入收取篮(in-basket)中。如果收取篮既不是空的也不是满的,Plodson将处理收取篮中最上面的文件,也可能取出车中的下一个文件,把它放入收取篮。他采取了自认为是比较鲁莽的行为----仍硬币来决定要才去的措施。
    可以用一个指针数组来模拟这种情况,其中的指针指向表示车中文件的字符串。每个字符串都包含所描述的人的姓名。可以用堆栈表示收取篮,并使用第二个指针数组来表示发出篮。通过将指针从输入数组压入到堆栈中来表示将文件添加到收取篮中,同时通过从堆栈中弹出项目,并将它添加到发出篮中来表示处理文件。

 

堆栈类的模拟:

  1. // testTemplate.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8. #include "ctime"  
  9.   
  10. template<typename Type>  
  11. class CStack  
  12. {  
  13. public:  
  14.     explicit CStack( int ss = SIZE );  
  15.     CStack( const CStack& st );  
  16.     ~CStack()  
  17.     {  
  18.         if ( items )  
  19.         {  
  20.             delete[] items;  
  21.         }  
  22.     }  
  23. public:  
  24.     bool isEmpty()  
  25.     {  
  26.         return ( 0 == m_nTop );  
  27.     }  
  28.     bool isFull()  
  29.     {  
  30.         return ( m_StackSize == m_nTop );  
  31.     }  
  32.     bool push( const Type& Item );  
  33.     bool pop( Type& Item );  
  34.     CStack& operator= ( const CStack& rCStack );  
  35. private:  
  36.     enum { SIZE = 10 };  
  37.     int m_StackSize;  
  38.     Type* items;  
  39.     int m_nTop;  
  40. };  
  41.   
  42. template<typename Type>  
  43. CStack<Type>::CStack( int ss /* = SIZE */ ) : m_StackSize( ss ), m_nTop( 0 )  
  44. {  
  45.     items = new Type[ m_StackSize ];  
  46. }  
  47.   
  48. template<typename Type>  
  49. CStack<Type>::CStack( const CStack<Type>& st )  
  50. {  
  51.     m_StackSize = st.m_StackSize;  
  52.     m_nTop = st.m_nTop;  
  53.     items = new Type[ st.m_StackSize ];  
  54.     for ( int i = 0; i < m_StackSize; i++ )  
  55.     {  
  56.         items[ i ] = st.items[ i ];  
  57.     }  
  58. }  
  59.   
  60. template<typename Type>  
  61. bool CStack<Type>::push( const Type& Item )  
  62. {  
  63.     if ( !isFull() )  
  64.     {  
  65.         items[ m_nTop ] = Item;  
  66.         m_nTop++;  
  67.         return true;  
  68.     }  
  69.     return false;  
  70. }  
  71.   
  72. template<typename Type>  
  73. bool CStack<Type>::pop( Type& Item )  
  74. {  
  75. /* 
  76.     if ( !isEmpty() ) 
  77.     { 
  78.         Item = items[ m_nTop ]; // 注意这样写是不对的,因为未满的时候items[ m_nTop ]指向未知 
  79.         m_nTop--; 
  80.         return true; 
  81.     }*/  
  82.     if ( m_nTop > 0)  
  83.     {  
  84.         Item = items[ --m_nTop ];  
  85.         return true;  
  86.     }  
  87.     return false;  
  88. }  
  89.   
  90. template<typename Type>  
  91. CStack<Type>& CStack<Type>::operator= ( const CStack<Type>& rCStack )  
  92. {  
  93.     if ( rCStack == *this)  
  94.     {  
  95.         return *this;  
  96.     }  
  97.     if ( items )  
  98.     {  
  99.         delete[] items;  
  100.     }  
  101.     m_StackSize = st.m_StackSize;  
  102.     m_nTop = st.m_nTop;  
  103.     items = new Type[ st.m_StackSize ];  
  104.     for ( int i = 0; i < m_StackSize; i++ )  
  105.     {  
  106.         items[ i ] = st.items[ i ];  
  107.     }  
  108. }  
  109.   
  110. const int NUM = 10;  
  111.   
  112. int _tmain(int argc, _TCHAR* argv[])  
  113. {  
  114.     srand( time( 0 ) );  
  115.     cout << "Please enter stack size:";  
  116.     int stacksize;  
  117.     cin >> stacksize;  
  118.     CStack< const char* > st( stacksize );  
  119.   
  120.     // in basket  
  121.     const char* in[ NUM ] = {  
  122.         "1:Hack Gilgamesh""2:KiKi Ishtar",  
  123.         "3:Betty Rocker",   "4:Ian Flagranti",  
  124.         "5:Wolfgang Kibble""6:Portia Koop",  
  125.         "7:Joy Almondo""8:Xaverie Parika",  
  126.         "9:Juan Moore""10:Misha Mache"  
  127.                             };  
  128.   
  129.     // out basket  
  130.     const char* out[ NUM ];  
  131.   
  132.     int processed = 0;  
  133.     int nextin = 0;  
  134.     while ( processed < NUM )  
  135.     {  
  136.         if ( st.isEmpty() )  
  137.         {  
  138.             st.push( in[ nextin++ ] );  
  139.         }  
  140.         else if ( st.isFull() )  
  141.         {  
  142.             st.pop( out[ processed++ ] );  
  143.         }  
  144.         else if ( rand() % 2 && nextin < NUM )  
  145.         {  
  146.             st.push( in[ nextin++ ] );  
  147.         }  
  148.         else  
  149.         {  
  150.             st.pop( out[ processed++ ] );  
  151.         }  
  152.     }  
  153.     for ( int i = 0; i < NUM; i++ )  
  154.     {  
  155.         cout << out[ i ] << endl;  
  156.     }  
  157.     cout << "Done." << endl;  
  158.   
  159.     return 0;  
  160. }  

 


数组模板范例和非类型参数
    模板常被用作容器类,这是因为类型参数的概念非常适合于将相同的存储方案用于不同的类型。确实,为容器类提供可重用代码是引入模板的主要动机。
    比如Array<double, 12> MyArray;其中的表达式参数可以是整形、枚举、引用或指针。因此,double m是不合法的,但double* r是合法的。另外,模板代码不能修改参数的值,也不能使用参数的地址。
    可以将用于常规类的技术用于模板类。模板类可用作基类,也可用作组件类,还可用作其他模板的类型参数。
1.递归使用模板

  1. // testTemplate2.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9. template<typename T, int n>  
  10. class MyArray  
  11. {  
  12. public:  
  13.     MyArray(){}  
  14.     explicit MyArray( const T& v );  
  15. public:  
  16.     virtual T& operator[]( int i );  
  17.     virtual T operator[]( int i ) const;  
  18. private:  
  19.     T ar[ n ];  
  20. };  
  21.   
  22. template<typename T, int n>   // init  
  23. MyArray<T, n>::MyArray( const T& v )  
  24. {  
  25.     for ( int i = 0; i < n; i++ )  
  26.     {  
  27.         ar[ i ] = v;  
  28.     }  
  29. }  
  30.   
  31. template<typename T, int n>   // init  
  32. T& MyArray<T, n>::operator[]( int i )  
  33. {  
  34.     if ( i < 0 || i >= n)  
  35.     {  
  36.         cerr << "Error in array limits:" << i << "  is out of range" << endl;  
  37.         exit( EXIT_FAILURE );  
  38.     }  
  39.     return ar[ i ];  
  40. }  
  41.   
  42. template<typename T, int n>   // init  
  43. T MyArray<T, n>::operator[]( int i ) const  
  44. {  
  45.     if ( i < 0 || i >= n)  
  46.     {  
  47.         cerr << "Error in array limits:" << i << "  is out of range" << endl;  
  48.         exit( EXIT_FAILURE );  
  49.     }  
  50.     return ar[ i ];  
  51. }  
  52.   
  53. int _tmain(int argc, _TCHAR* argv[])  
  54. {  
  55.     MyArray<int ,10> sums;  
  56.     MyArray<double, 10> aves;  
  57.     MyArray< MyArray<int, 5>, 10 > twodee;  
  58.   
  59.     int i, j;  
  60.   
  61.     for ( i = 0; i < 10; i++ )  
  62.     {  
  63.         sums[ i ] = 0;  
  64.         for ( j = 0; j < 5; j++ )  
  65.         {  
  66.             twodee[ i ][ j ] = ( i + 1 ) * ( j + 1 );  
  67.             sums[ i ] += twodee[ i ][ j ];  
  68.         }  
  69.         aves[ i ] = ( double )sums[ i ] / 10;  
  70.     }  
  71.   
  72.     for ( i = 0; i < 10; i++ )  
  73.     {  
  74.         for ( j = 0; j < 5; j++ )  
  75.         {  
  76.             cout.width( 2 );  
  77.             cout << twodee[ i ][ j ] << "   ";  
  78.         }  
  79.         cout << ":sum = ";  
  80.         cout.width( 3 );  
  81.         cout << sums[ i ] << ", average = " << aves[ i ] << endl;  
  82.     }  
  83.   
  84.     cout << "Done." << endl;  
  85.   
  86.   
  87.     return 0;  
  88. }  

MyArray< MyArray<int, 5>, 10 > twodee;这使得twodee是一个包含10个元素的数组,其中每个元素都是一个包含5个int元素的数组。与之等价的常规数组声明如下:int twodee[ 10 ][ 5 ];在模板句法中,维的顺序与等价的二维数组相反。


2.模板中使用多个类型参数
    模板可以保护多个类型参数。例如,假设希望类可以保存两种值,则可以创建并使用Pair模板来保存两个不同的值(标准模板库提供了类似的模板,名为pair)。

  1. // testPair.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9. template<typename T1, typename T2>  
  10. class CPair  
  11. {  
  12. public:  
  13.     CPair(){}  
  14.     CPair( const T1& aval, const T2 bval ) : a( aval ), b( bval )  
  15.     {  
  16.     }  
  17. public:  
  18.     T1& first()  
  19.     {  
  20.         return a;  
  21.     }  
  22.     T2& second()  
  23.     {  
  24.         return b;  
  25.     }  
  26.     T1& first() const { return a }  
  27.     T2& second() const { return b }  
  28. private:  
  29.     T1 a;  
  30.     T2 b;  
  31. };  
  32.   
  33. int _tmain(int argc, _TCHAR* argv[])  
  34. {  
  35.     CPair<string, int> ratings[ 4 ] =  
  36.     {  
  37.         CPair<string, int>( "The Purple Duke", 5 ),  
  38.         CPair<string, int>( "Jake's Frisco Al Fresco", 4 ),  
  39.         CPair<string, int>( "Mont Souffle", 5 ),  
  40.         CPair<string, int>( "Gertie's Eats", 3 ),  
  41.     };  
  42.     int joins = sizeof( ratings ) / sizeof( CPair<string, int> );  
  43.     cout << "Raring:\tEatery\n";  
  44.     for ( int i = 0; i < joins; i++ )  
  45.     {  
  46.         cout << ratings[ i ].second() << ":\t" << ratings[ i ].first() << endl;  
  47.     }  
  48.     cout << "Oops ! Revised rating:" << endl;  
  49.     ratings[ 3 ].first() = "Gertie's Fab Eat";  
  50.     ratings[ 3 ].second() = 6;  
  51.     cout << ratings[ 3 ].second() << ":\t" << ratings[ 3 ].first() << endl;  
  52.     cout << "Done." << endl;  
  53.   
  54.   
  55.     return 0;  
  56. }  


 

模板的具体化
    类模板与函数模板很相似,因为可以有隐式实例化、显示实例化和显示具体化,他们统称为具体化(specialization)。模板以通用类型的方式描述类,而具体化是使用具体的类型生成类声明。

1.隐式实例化
    一般的永华都是隐式实例化(implicit instantiation),即他们声明一个活多个对象,指出所需的类型,而编译器使用通用模板提供的处方生成具体的类定义

2.显示实例化
    当使用关键字template并支出所需类型来声明类时,编译器将生成类声明的显示实例化(explicit insantiation)。声明必须位于模板定义所在的名称空间中。例如,
template class MyArray<string, 100>
将MyArray<string, 100>声明为一个类。在这种情况下,虽然没有创建或提及类对象,编译器也将生成类声明(包括方法定义)。和隐式实例化一样,也将根据通用模板来生成具体化。

3.显示具体化(explicit specialization)
    显示具体化是特定类型(用于替换模板的通用类型)的定义。有时候,可能需要在为特殊类型实例化时,对模板进行修改,使其行为不同。在这种情况下,可以创建显示具体化。例如:
template<typename T>
class CSortedArray
{};
在排序的时候,使用>操作符来对值进行比较。对于数字,这管用;如果T表示一种类,则只用定义了T::operator>()方法,这也管用;但如果T是有char*表示的字符串,这将不管用。所以需要对其具体化
template<> class CSortedArray<char *>
{};

4.部分具体化
    c++还允许部分具体化(partial specialization),即部分限制模板的通用性。例如,部分具体化可以给类型参数之一指定具体的类型
template<class T1, class T2> class CPair {};
template<class T1> class CPair<T1, int> {}:
关键字后面的<>声明的是没有被具体化的类型参数。因此,上述第二个声明将T2具体化为int,但T1保存不变。注意,如果指定所有的类型,则<>内将为空,这将导致显示具体化。
template<> class CPair<int, int> {};

  1. // testParSpe.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7.   
  8. templatetypename T1, typename T2 >  
  9. class Test  
  10. {  
  11. public:  
  12.     Test( T1 a, T2 b )  
  13.     {  
  14.         m_a = a;  
  15.         m_b = b;  
  16.     }  
  17.     void show()  
  18.     {  
  19.         cout << "the a value is:" << m_a << endl;  
  20.         cout << "the b value is:" << m_b << endl;  
  21.     }  
  22. private:  
  23.     T1 m_a;  
  24.     T2 m_b;  
  25. };  
  26.   
  27. templatetypename T1 >  
  28. class Test< T1, int >  
  29. {  
  30. public:  
  31.     Test( T1 a, int b )  
  32.     {  
  33.         m_a = a;  
  34.         m_b = b;  
  35.     }  
  36.     void show()  
  37.     {  
  38.         cout << "this template< typename T1 >, the a value is:" << m_a << endl;  
  39.         cout << "this template< typename T1 >, the b value is:" << m_b << endl;  
  40.     }  
  41. private:  
  42.     T1 m_a;  
  43.     int m_b;  
  44. };  
  45.   
  46. int _tmain(int argc, _TCHAR* argv[])  
  47. {  
  48.     Test< doubleint > test( 20.1, 4 );  
  49.     test.show();  
  50.   
  51.     return 0;  
  52. }  


 

成员模板
    C++模板支持的另一个新特性是:模板可用作结构、类或模板类的成员。要完成时限STL的设计,必须要使用这项特性。
  1. // testTemplateFriend.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9. template <typename T>  
  10. class CBeta  
  11. {  
  12. public:  
  13.     CBeta( T t, int i ) : q( t ), n( i )  
  14.     {}  
  15.     template<typename U>  
  16.     U blab( U u, T t )  
  17.     {  
  18.         return ( n.Value() + q.Value() ) * u / t;  
  19.     }  
  20.     void show() const  
  21.     {  
  22.         q.show();  
  23.         n.show();  
  24.     }  
  25. private:  
  26.     template<typename V>  
  27.     class CHold  
  28.     {  
  29.     public:  
  30.         CHold( V v = 0 ) : val( v ){}  
  31.         void show() const { cout << val << endl; }  
  32.         V Value() const { return val; }  
  33.     private:  
  34.         V val;  
  35.     };  
  36.     CHold<T> q;  
  37.     CHold<int> n;  
  38. };  
  39.   
  40. int _tmain(int argc, _TCHAR* argv[])  
  41. {  
  42.     CBeta<double> quy( 3.5, 3 );  
  43.     quy.show();  
  44.     cout << quy.blab( 10, 2.3 ) << endl;  
  45.     cout << "Done." << endl;  
  46.   
  47.   
  48.     return 0;  
  49. }  

在这个程序中CHold模板是在私有部分声明的,因此只能在CBeta类中访问他。CBeta类使用CHold模板声明了两个数据成员:
CHold<T> q;
CHold<int> n;
n是基于int类型的CHold对象,而q成员是基于T类型(CBeta模板参数)的CHold对象。

 

将模板用作参数
    模板可以包含类型参数(如typename T)和非类型参数(例如int n)。模板还可以包含本身就是模板的参数。这种参数是模板新增的特性,用于实现STL。

  1. // testTemplateParam.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8. #include "ctime"  
  9.   
  10. template<typename Type>  
  11. class CStack  
  12. {  
  13. public:  
  14.     explicit CStack( int ss = SIZE );  
  15.     CStack( const CStack& st );  
  16.     ~CStack()  
  17.     {  
  18.         if ( items )  
  19.         {  
  20.             delete[] items;  
  21.         }  
  22.     }  
  23. public:  
  24.     bool isEmpty()  
  25.     {  
  26.         return ( 0 == m_nTop );  
  27.     }  
  28.     bool isFull()  
  29.     {  
  30.         return ( m_StackSize == m_nTop );  
  31.     }  
  32.     bool push( const Type& Item );  
  33.     bool pop( Type& Item );  
  34.     CStack& operator= ( const CStack& rCStack );  
  35. private:  
  36.     enum { SIZE = 10 };  
  37.     int m_StackSize;  
  38.     Type* items;  
  39.     int m_nTop;  
  40. };  
  41.   
  42. template<typename Type>  
  43. CStack<Type>::CStack( int ss /* = SIZE */ ) : m_StackSize( ss ), m_nTop( 0 )  
  44. {  
  45.     items = new Type[ m_StackSize ];  
  46. }  
  47.   
  48. template<typename Type>  
  49. CStack<Type>::CStack( const CStack<Type>& st )  
  50. {  
  51.     m_StackSize = st.m_StackSize;  
  52.     m_nTop = st.m_nTop;  
  53.     items = new Type[ st.m_StackSize ];  
  54.     for ( int i = 0; i < m_StackSize; i++ )  
  55.     {  
  56.         items[ i ] = st.items[ i ];  
  57.     }  
  58. }  
  59.   
  60. template<typename Type>  
  61. bool CStack<Type>::push( const Type& Item )  
  62. {  
  63.     if ( !isFull() )  
  64.     {  
  65.         items[ m_nTop ] = Item;  
  66.         m_nTop++;  
  67.         return true;  
  68.     }  
  69.     return false;  
  70. }  
  71.   
  72. template<typename Type>  
  73. bool CStack<Type>::pop( Type& Item )  
  74. {  
  75.     /* 
  76.     if ( !isEmpty() ) 
  77.     { 
  78.     Item = items[ m_nTop ]; // 注意这样写是不对的,因为未满的时候items[ m_nTop ]指向未知 
  79.     m_nTop--; 
  80.     return true; 
  81.     }*/  
  82.     if ( m_nTop > 0)  
  83.     {  
  84.         Item = items[ --m_nTop ];  
  85.         return true;  
  86.     }  
  87.     return false;  
  88. }  
  89.   
  90. template<typename Type>  
  91. CStack<Type>& CStack<Type>::operator= ( const CStack<Type>& rCStack )  
  92. {  
  93.     if ( rCStack == *this)  
  94.     {  
  95.         return *this;  
  96.     }  
  97.     if ( items )  
  98.     {  
  99.         delete[] items;  
  100.     }  
  101.     m_StackSize = st.m_StackSize;  
  102.     m_nTop = st.m_nTop;  
  103.     items = new Type[ st.m_StackSize ];  
  104.     for ( int i = 0; i < m_StackSize; i++ )  
  105.     {  
  106.         items[ i ] = st.items[ i ];  
  107.     }  
  108. }  
  109.   
  110.   
  111. templatetemplate<typename T> class Thing >  
  112. class Crab  
  113. {  
  114. public:  
  115.     Crab(){}  
  116.     bool push( int iA, double fB )  
  117.     {  
  118.         return ( s1.push( iA ) && s2.push( fB ) );  
  119.     }  
  120.     bool pop( int& iA, double& fB )  
  121.     {  
  122.         return ( s1.pop( iA ) && s2.pop( fB ) );   
  123.     }  
  124. private:  
  125.     Thing<int> s1;  
  126.     Thing<double> s2;  
  127. };  
  128.   
  129.   
  130. int _tmain(int argc, _TCHAR* argv[])  
  131. {  
  132.     Crab<CStack> nebula;  
  133.     int nj;  
  134.     double nb;  
  135.     cout << "Enter int double pairs, such as 4 3.5 ( 0 0 to be end):" << endl;  
  136.     while ( cin >> nj >> nb && nj > 0 && nb > 0 )  
  137.     {  
  138.         if ( !nebula.push( nj, nb ) )  
  139.         {  
  140.             break;  
  141.         }  
  142.     }  
  143.     while ( nebula.pop( nj, nb) )  
  144.     {  
  145.         cout << nj << ", " << nb << endl;  
  146.     }  
  147.     cout << "Done." << endl;  
  148.   
  149.   
  150.     return 0;  
  151. }  

在这个类里还可以使用模板参数和常规参数,例如:
template< template<typename t> class Thing, typename U, typename V>
class Crab
{
private:
   Thing<U> s1;
   Thing<V> s2;
}


模板类和友元
    模板类声明也可以有友元。模板的友元分3类:
1.非模板友元

  1. // testTemplateFriend2.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9. template<typename T>  
  10. class CHasFriend  
  11. {  
  12. public:  
  13.     CHasFriend( const T& t ) : item( t )  
  14.     {  
  15.         ct++;  
  16.     }  
  17.     ~CHasFriend()  
  18.     {  
  19.         ct--;  
  20.     }  
  21.     friend void counts();  
  22.     friend void report( const CHasFriend<T>& );  
  23. private:  
  24.     explicit CHasFriend( const CHasFriend& rCHasFriend ){}  
  25. private:  
  26.     T item;  
  27.     static int ct;  
  28. };  
  29.   
  30. template<typename T>  
  31. int CHasFriend<T>::ct = 0;  
  32.   
  33. void counts()  
  34. {  
  35.     cout << "int count:" << CHasFriend<int>::ct;  
  36.     cout << "   double count:" << CHasFriend<double>::ct << endl;  
  37. }  
  38.   
  39. void report( const CHasFriend<int>& hf )  
  40. {  
  41.     cout << "CHasFriend item:" << hf.item << endl;  
  42. }  
  43.   
  44. void report( const CHasFriend<double>& hf )  
  45. {  
  46.     cout << "CHasFriend item:" << hf.item << endl;  
  47. }  
  48.   
  49. int _tmain(int argc, _TCHAR* argv[])  
  50. {  
  51.     cout << "No objects declared:";  
  52.     counts();  
  53.   
  54.     CHasFriend<int> hfil1( 10 );  
  55.     cout << "After hfil1 declared:";  
  56.     counts();  
  57.   
  58.     CHasFriend<int> hfil2( 20 );  
  59.     cout << "After hfil2 declared:";  
  60.     counts();  
  61.   
  62.     CHasFriend<double> hfdb( 10.5 );  
  63.     cout << "After hfdb declared:";  
  64.     counts();  
  65.   
  66.     report( hfil1 );  
  67.     report( hfil2 );  
  68.     report( hfdb );  
  69.   
  70.   
  71.     return 0;  
  72. }  

代码中声明使counts()函数成为模板所有实例化的友元。它内部的CHasFriend<int>和CHasFriend<double>是针对不同的模板的。


2.约束(bound)模板友元,即友元的类型取决于类呗实例化时的类型

  1. // testTemplateFriend3.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9.   
  10. template<typename T>  
  11. void counts()  
  12. {  
  13.     cout << "this count value is:" << CHasFriend<T>::ct << endl;  
  14. }  
  15.   
  16. template<typename T>  
  17. void report( const T& hr )  
  18. {  
  19.     cout << "this count value is:" << hr.m_item << endl;  
  20. }  
  21.   
  22. template<typename TT>  
  23. class CHasFriend  
  24. {  
  25. public:  
  26.     CHasFriend( const TT item ) : m_item( item )  
  27.     {  
  28.         ct++;  
  29.     }  
  30.     ~CHasFriend()  
  31.     {  
  32.         ct--;  
  33.     }  
  34.     friend void counts<TT>();  
  35.     friend void report<>( const CHasFriend<TT>& hr );  
  36. private:  
  37.     explicit CHasFriend( const CHasFriend& rCHasFriend ){}  
  38. private:  
  39.     TT m_item;  
  40.     static int ct;  
  41. };  
  42.   
  43. template<typename T>  
  44. int CHasFriend<T>::ct = 0;  
  45.   
  46. int _tmain(int argc, _TCHAR* argv[])  
  47. {  
  48.     counts<int>();  
  49.     CHasFriend<int> hfil( 10 );  
  50.     CHasFriend<int> hfi2( 20 );  
  51.     CHasFriend<double> hfdb( 10.5 );  
  52.   
  53.     report( hfil );  
  54.     report( hfi2 );  
  55.     report( hfdb );  
  56.   
  57.     cout << "counts<int>() output :" << endl;  
  58.     counts<int>();  
  59.     cout << "counts<double>() output :" << endl;  
  60.     counts<double>();  
  61.   
  62.   
  63.     return 0;  
  64. }  

声明中的<>指出这是模板具体化。对于report(),<>可以为空,这是因为可以从函数参数推断出模板类型参数(CHasFriend<TT>)。不过,也可以使用report< CHasFriend<TT> >( CHasFriend<TT>& )。但counts()函数没有参数,因此必须使用模板参数句法(<TT>)来指明其具体化。还需要注意的是,TT是CHasFriend类的参数类型。

 

3.非约束(unbound)模板友元,即友元的所有具体化都是类的每一个具体化的友元

  1. // testTemplateFriend4.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "string"  
  8.   
  9. template<typename T>  
  10. class CManyFriend  
  11. {  
  12. public:  
  13.     CManyFriend( const T& i ) : item( i )  
  14.     {  
  15.     }  
  16.     template<typename C, typename D> friend void show( C&, D& );  
  17. private:  
  18.     T item;  
  19. };  
  20.   
  21. template<typename C, typename D>void show( C& c, D& d )  
  22. {  
  23.     cout << c.item << "   " << d.item << endl;  
  24. }  
  25.   
  26.   
  27.   
  28. int _tmain(int argc, _TCHAR* argv[])  
  29. {  
  30.     CManyFriend<int> hfil( 10 );  
  31.     CManyFriend<int> hfil2( 20 );  
  32.     CManyFriend<double> hfdb( 10.5 );  
  33.   
  34.     cout << "hfil, hfil2:";  
  35.     show( hfil, hfil2 );  
  36.   
  37.     cout << "hfil2, hfdb:";  
  38.     show( hfil2, hfdb );  
  39.   
  40.     return 0;  
  41. }  

前面的1、2,int类具体化获得int函数具体化,依此类推。通过在类内部声明模板,可以创建非约束友元函数,即每个函数具体化都是每个类具体化的友元。对于非约束友元,友元模板类型参数与模板类类型参数是不同的:
template<typename C, typename D> friend void show( C&, D& );
但前提是必须在类内部声明模板

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值