// C8_8.cpp : Defines the entry point for the console application. // 間接資料成員存取 #include "stdafx.h" #include using namespace std; class CaseBox // 類別定義於全域範圍 { public: CaseBox(double lv = 3.0, double wv= 3.0, double hv= 3.0) // 建構子定義 { cout << endl << "呼叫建構子"; m_L = lv; // 設定資料成員 m_W = wv; m_H = hv; } double Area() // 宣告類別成員函式 { return 2.0 * (m_L*m_W + m_W*m_H + m_L*m_H); } int Compare(CaseBox* pBox) { return this->Area() > pBox->Area(); } private: double m_L; //類別資料成員 double m_W; double m_H; }; int main(int argc, char* argv[]) { CaseBox MyCase[5]; // Array of CBox objects declared CaseBox S1(6.0, 6.0 ,6.0); // 宣告類別變數 CaseBox S2; double area1 = 0.0; double area2 = 0.0; // 計算表面積 area1 = S1.Area(); area2 = S2.Area(); cout << endl << " S1 表面積 = " << area1 << " 平方公分" ; cout << endl << " S2 表面積 = " << area2 << " 平方公分\n" ; CaseBox* p1 = &S1; // 指向 S1物件位址 ,初始化指標 CaseBox* p2 = 0; // Pointer to CaseBox initialized to null cout << endl << "S1 位址 : " << p1 //顯示位址 << endl << "S1 表面積 : " << p1->Area(); p2 = &S2; if(p2->Compare(p1)) // 經由指標比較 cout << endl << "S2 大於 S1"; else cout << endl << "S2 小於或等於 S1"; p1 = MyCase; // 設定為陣列位址 MyCase[2] = S2; // 設定第三個元素為 S2 cout << endl // 經由指標存取 << "MyCase[2] 表面積為 : " << (p1 + 2)->Area(); cout << endl; cout << endl // 顯示佔用記憶體大小 << "一個 CaseBox 物件佔用 " << sizeof S1 << " 位元組。\n"; cout << endl; return 0; }