但是,如果確實存在著對所有派生類(或僅僅對某些派生類)都有用的公共信息時怎么辦呢?可以簡單把這些信息封裝成類,然后從它派生出實現部分的類:
class Shape {
public: //使用Shapes的用戶的接口
virtual void draw() const = 0;
virtual void rotate(int degrees) = 0;
virtual Point center() const = 0;
// ...
// no data
};
struct Common {
Color col;
// ...
};
class Circle : public Shape, protected Common {
public:
void draw() const;
void rotate(int) { }
Point center() const { return center; }
// ...
protected:
Point cent;
int radius;
};
class Triangle : public Shape, protected Common {
public:
void draw() const;
void rotate(int);
Point center() const;
// ...
protected:
Point a, b, c;
};
為什么一個空類的大小不為0?
要清楚,兩個不同的對象的地址也是不同的;谕瑯拥睦碛,new總是返回指向不同對象的指針。
看看:
class Empty { };
void f()
{
Empty a, b;
if (&a == &b) cout << "impossible: report error to compiler supplier";
Empty* p1 = new Empty;
Empty* p2 = new Empty;
if (p1 == p2) cout << "impossible: report error to compiler supplier";
}
有一條有趣的規則:一個空的基類并不一定有分隔字節。
文章來源于領測軟件測試網 http://www.kjueaiud.com/