¡¡ÈôÄú¼Ì³ÐÁËij¸öÀà±ðÖ®áá
£¬µ±ÄúÔÚÉú³ÉÑÜÉúÀà±ðµÄÎï¼þʱÈô²»Ö¸¶¨²ÎÊý
£¬ÎÞ²ÎÊýµÄÔ¤É轨¹¹×ӻᱻִÐУ¬¶ø»ù´¡Àà±ðµÄÎÞ²ÎÊýÔ¤É轨¹¹×ÓÒ²»á±»Ö´ÐУ¬ËùÒÔ»ùì¶ÕâÖÖÌØÐÔ£¬Í¨³£Ô¤É轨¹¹×ÓÖлá׫дһЩͨÓõijÉԱ״̬³õʼ£¬ÀýÈçÉ趨һЩԤÉèÖµ
¡£¡¡¡¡Èç¹û¼Ì³ÐÖ®áᣬÄúҪʹÓÃÑÜÉúÀà±ðÉú³ÉÎï¼þ£¬ÔÚÉú³ÉÎï¼þʱָ¶¨²ÎÊý£¬²¢Í¬Ê±Ö´Ðлùµ×Àà±ðÖеÄij¸ö²ÎÊý½¨¹¹×Ó£¬Äú¿ÉÒÔʹÓà : ÔËËã×Ó
ÀýÈ磺
// Point2DÀà±ð
class Point2D {
public:
Point2D() {
_x = 0;
_y = 0;
}
Point2D(int x, int y) : _x(x), _y(y) {
}
private:
int _x;
int _y;
};
// Point3DÀà±ð
class Point3D : public Point2D { // ¼Ì³ÐPoint2DÀà±ð
public:
Point3D() {
_z = 0;
}
// ½¨¹¹º¯Ê½£¬Í¬Ê±Ö¸¶¨ºô½Ð¸¸Àà±ð½¨¹¹º¯Ê½
Point3D(int x, int y, int z) : Point2D(x, y), _z(z) {
}
private:
int _z; // ÐÂÔö˽ÓÃ×ÊÁÏ
};
¡¡¡¡Èç¹ûÄúʹÓÃÑÜÉúÀà±ðÉú³ÉÎï¼þ£¬Ôò½¨¹¹º¯Ê½µÄÖ´ÐÐ˳Ðò»á´Ó»ùµ×Àà±ðµÄ½¨¹¹º¯Ê½¿ªÊ¼Ö´ÐÐÆð£¬ÕâÊÇ¿ÉÒÔÀí½âµÄ£¬ÒòΪ»ùµ×Àà±ðÊÇÑÜÉúÀà±ðµÄ»ù´
¡£¬Ò»Ð©»ù´¡µÄ²ÎÊý»ò³õʼ״̬±ØÐëÏÈÍê³É£¬ÔÙÀ´ÔÙÍê³ÉÑÜÉúÀà±ðÖеĽ¨¹¹º¯Ê½¡£
¡¡¡¡¶øÔÚÎï¼þ±»ÏûÃðʱ£¬½â¹¹º¯Ê½µÄÖ´ÐÐ˳ÐòÔòÕýºÃÏà·´£¬ÊÇ´ÓÑÜÉúÀà±ðµÄ½â¹¹º¯Ê½¿ªÊ¼Ö´ÐУ¬ÔÙÀ´²ÅÊÇ»ù´¡Àà±ðµÄ½¨¹¹º¯Ê½£¬ÒòΪÈô»ùµ×Àà±ðµÄ½â¹¹º¯Ê½Èç¹ûÏÈÖ´ÐУ¬ÔòÑÜÉúÀà±ðÏàÒÀ춻ùµ×Àà±ðµÄһЩ״̬Ҳ»á±»½â¹¹£¨ÀýÈçÖ¸±ê£©£¬Ôò´ËʱÔÙÐÐÑÜÉúÀà±ðµÄ½â¹¹º¯Ê½£¬½«´æÔÚ×ÅÏàÒÀÎÊÌâ¶øÔì³É´íÎó¡£
¡¡¡¡ÏÂÃæÕâ¸ö¼òµ¥µÄ³Ìʽ¿ÉÒÔ¸æËßÄú½¨¹¹º¯Ê½Óë½â¹¹º¯Ê½£¬Ôڼ̳ÐÖ®ááµÄÖ´ÐÐ˳Ðò£º
#include <iostream> using namespace std; class Foo1 { public:
Foo1() {
cout << "Foo1½¨¹¹º¯Ê½" << endl;
}
~Foo1()
{
cout << "Foo1½â¹¹º¯Ê½" << endl;
}
};
class Foo2 : public Foo1 { public:
Foo2() {
cout << "Foo2½¨¹¹º¯Ê½" << endl;
}
~Foo2() {
cout << "Foo2½â¹¹º¯Ê½" << endl;
}
};
int main()
{
Foo2 f;
cout << endl;
return 0;
}
Ö´Ðнá¹û£º
Foo1½¨¹¹º¯Ê½
Foo2½¨¹¹º¯Ê½
Foo2½â¹¹º¯Ê½
Foo1½â¹¹º¯Ê½