# 巢狀類別（Nested Classes）

class OuterClass {
private:
class InnerClass {
//  ....
};
};

• PointDemo.h
class PointDemo {
public:
PointDemo(int);
~PointDemo();

void show();
private:
// Nested Class
class Point {
public:
Point();
Point(int, int);
int x() { return _x; }
int y() { return _y; }
void x(int x) { _x = x; }
void y(int y) { _y = y; }
private:
int _x;
int _y;
};

Point **_points;
int _length;
};

• PointDemo.cpp
#include <iostream>
#include "PointDemo.h"
using namespace std;

// 實作內部類別
PointDemo::Point::Point() {
_x = 0;
_y = 0;
}

// 實作內部類別
PointDemo::Point::Point(int x, int y) {
_x = x;
_y = y;
}

PointDemo::PointDemo(int length) : _length(length) {
_points = new Point*[_length];
for(int i = 0; i < _length; i++) {
_points[i] = new Point();
_points[i]->x(i*5);
_points[i]->y(i*5);
}
}

void PointDemo::show() {
for(int i = 0; i < _length; i++) {
cout << "(x, y) = ("
<< _points[i]->x() << ", "
<< _points[i]->y() << ")"
<< endl;
}
}

PointDemo::~PointDemo() {
for(int i = 0; i < _length; i++) {
delete _points[i];
}
delete [] _points;
}

• main.cpp
#include <iostream>
#include "PointDemo.h"
using namespace std;

int main() {
PointDemo demo(10);
demo.show();
return 0;
}

(x, y) = (0, 0)
(x, y) = (5, 5)
(x, y) = (10, 10)
(x, y) = (15, 15)
(x, y) = (20, 20)
(x, y) = (25, 25)
(x, y) = (30, 30)
(x, y) = (35, 35)
(x, y) = (40, 40)
(x, y) = (45, 45)

class PointDemo {
...

private:

// Nested Class
class Point {

friend class PointDemo;
....
};
....
};

class PointDemo {
public:
...
friend class Point;

private:
// Nested Class
class Point {
....
};
....
};

• PointDemo.h
class PointDemo {
public:
PointDemo(int);
~PointDemo();

void show();
private:

// Nested Class
class Point;

Point **_points;
int _length;
};

• Point.h
class PointDemo::Point {
public:
Point();
Point(int, int);
int x() { return _x; }
int y() { return _y; }
void x(int x) { _x = x; }
void y(int y) { _y = y; }
private:
int _x;
int _y;
};

• PointDemo.cpp
#include <iostream>
#include "PointDemo.h"
#include "Point.h"
using namespace std;

PointDemo::PointDemo(int length) : _length(length) {
_points = new Point*[_length];
for(int i = 0; i < _length; i++) {
_points[i] = new Point();
_points[i]->x(i*5);
_points[i]->y(i*5);
}
}

void PointDemo::show() {
for(int i = 0; i < _length; i++) {
cout << "(x, y) = ("
<< _points[i]->x() << ", "
<< _points[i]->y() << ")"
<< endl;
}
}

PointDemo::~PointDemo() {
for(int i = 0; i < _length; i++) {
delete _points[i];
}
delete [] _points;
}

• Point.cpp
#include "PointDemo.h"
#include "Point.h"

PointDemo::Point::Point() {
_x = 0;
_y = 0;
}

PointDemo::Point::Point(int x, int y) {
_x = x;
_y = y;
}