類別也可以定義於函式之中,稱之為區域類別(Local
classes),定義於函式中的區域類別只在該函式範圍(Scope)中有作用,也因此區域類別的宣告與定義都必須在該函式中完成。
區域類別中的成員通常宣告為"public",作用常是為了方便資料的群組管理,區域類別的定義常是很簡單的,例如:
#include <iostream> using namespace std;
int main() { // 區域類別 class Point { public: int x; int y; Point(int x, int y) { this->x = x; this->y = y; } }; Point p(10, 10);
cout << "(x, y) = (" << p.x << ", " << p.y << ")" << endl; return 0; }
執行結果:
區域類別不可以直接存取所在函式中的變數,可以存取外圍類別的私用成員。
|
|