[cpp] <span style="font-size:18px;"></span> //============================================================================ // Name : 11.cpp // Author : zhaoming // Version : // Copyright : copyright to zhaoming // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class INTSET; //不完整聲明或前向聲明 class REALSET{ float *elems; int card,maxcard; public: REALSET(INTSET &s); ~REALSET(){ delete elems; } }; class INTSET{ int *elems,card,maxcard; //注意:不能在一個類的內部定義另一個類的成員函數,但可以聲明 /* * 課本上是這樣寫的 * friend double REALSET::REALSET(INTSET &s)//自動成為inline函數 { //本函數聲明為INTSET的友元後,可直接訪問INTSET的成員 elems = new float[maxcard = s.maxcard]; card = s.card; for(int i = 0; i < card; i++){ elems[i] = s.elems[i]; } } */ friend REALSET::REALSET(INTSET &s);//自動成為inline函數 public: INTSET(int maxcard); ~INTSET(){ delete elems; } int getcard(){ return card; } int getelems(int i){ return elems[i]; } }; REALSET::REALSET(INTSET &s) { //本函數聲明為INTSET的友元後,可直接訪問INTSET的成員 elems = new float[maxcard = s.maxcard]; card = s.card; for(int i = 0; i < card; i++){ elems[i] = s.elems[i]; } } INTSET::INTSET(int max){ elems = new int[maxcard = max]; card = 0; } int main() { INTSET iset(20); REALSET rset(iset); }