// other methods
protected:
TheOnlyInstance () {)
private:
// private data
通过将TheOnlyInstance构造函数声明为protected,并省略公有构造函数,可以防止局部实例被创建:
int main ()
TheOnlyInstance noCanDo: // not allowed
只能通过公有静态方法GetTheOnlylnstance来访问类。该方法被调用时,将返回类TheOnlyInstance的
实例
TheOnlyInstance* TheOnlyInstance :: GetTheOnlyInstance ()
static TheOnlyInstance objTheOnlyInstance:
return sobjTheOnlyInstance:
GetTheOnlyInstance方法仅在第一次被调用时,创建TheOnlyInstance类的一个实例。以这种方式构造
的静态对象一直有效,直到程序终止,此时这种静态对象将自动被释放。要检索指向这个类的惟一一个实
例的指针,只需要调用静态方法GetTheOlyInstance,该方法返国单对象的地址:
TheOnlyInstance* pTheOnlyInstance = TheOnlyInstance: : GetTheOnlyInstance () ;
因为静态变量在函数调用结束后仍保存在内存中,所以以后再调用GetTheOnlyInstance时,将返回同
一个静态对象的地址。
13.6
// x-coordinate of the ellipse's center
// y-coordinate of the ellipse's center
// semimajor axis
// semiminor axis
抽象基类
至此,介绍了简单继承和较复杂的多态继承。接下来更为复杂的是抽象基类(abstract base class,ABC)。
我们来看一些可使用ABC的编程情况。
有时候,使用is-a规则并不像看上去的那样简单。例如,假设您正在开发一个图形程序,该程序会显
示圆和椭圆等。圆是椭圆的一个特殊情况 -- 长轴和短轴等长的椭圆。因此,所有的圆都是椭圆,可以从
Ellipse类派生出Circle类。但涉及到细节时,将发现许多问题。
首先考虑 Ellipse 类包含的内容。数据成员可以包括椭圆中心的坐标、长半轴(长轴的一半)、短半轴
(短轴的一半)以及方向角(水平坐标轴与长轴之间的角度)。另外,还可以包括一些移动椭圆、返回椭圆
面积、旋转椭圆以及缩放长半轴和短半轴的方法:
class Ellipse
private:
double x:
double y:
double a:
double b:
double angle: // orientation angle in degrees
public:
...
void Move (int nx. ny) | x = nx; y = ny: }
virtual double Area()const { return 3.14159 * a * b: )
virtual void Rotate (double nang) | angle += nang: }
virtual void Scale (double sa, double sb) ( a *= sa: b *= sb: }
1: