我想應該還有很多人搞不清楚他的用處吧?
其實 class inheritance 真的是在 C++ 裏面很常被用到的技巧,
他的好處必須配合 polymorphism (virtual functions) 才能真正體會出來.
底下兩個程式: inh.cpp & noinh.cpp 做一樣的事情,
利用 virutal function 可以將各個 class 不同的 function definitions
define 在各個 class 裏面 (A::f(), B::f()),
而透過 base class 的介面 (P::f()) 來呼叫.
試想,
程式裡面的 "P *arr[4];" 如果他的 types (A or B)
是在 runtime 才由使用者或是 testcase 決定,
那麼顯然不能寫成 "A *arr[4]" or "B *arr[4]",
不過為了要記住各個 element 的 type,
傳統 C 的作法就是在 class P 裏面加一個 data member "int _type",
(注意這樣也是跟 virtual table pointer 一樣多了 4 Bytes)
然後在 member functions (如 f()) 再用 "switch(_type)... case" 來寫,
這樣的問題在於當 types 越來越多時,
你的 switch-cases 就會越變越大,
不但 compile & run time 會變差, 而且 code 也變得不好 maintain.
相對的, 利用 polymorphism 的話每增加一個新的 type 就是新增加一個 derived class,
對於必須要 specialized 的 virtual functions
就把它們 implement 在 derived class 裏面,
其它的就使用 base class 的 function 就好了,
這樣子一來新增 type 的時候就只要改 local class 的 member functions
(而不是整個 code 都要看過再對每一個 swith-case 去做修改)
而不用去動到 base class 或是其他 class 的 clde.
希望大家能夠通透, 這個太重要了...
====== inh.cpp ======
#include <iostream>
using namespace std;
class P
{
public:
virtual void f() const { cout << "P" << endl; }
};
class A : public P
{
public:
void f() const { cout << "A" << endl; }
};
class B : public P
{
public:
void f() const { cout << "B" << endl; }
};
void x(P* p)
{
p->f();
}
int main()
{
P *arr[4];
arr[0] = new A;
arr[1] = new B;
arr[2] = new B;
arr[3] = new P;
for (int i = 0; i < 4; ++i)
x(arr[i]);
cout << endl;
}
====== noinh.cpp ======
#include <iostream>
using namespace std;
class P
{
public:
P(int i) : _type(i) {}
virtual void f() const {
switch(_type) {
case 0: cout << "A" << endl; break;
case 1: cout << "B" << endl; break;
default: cout << "P" << endl; break;
}
}
private:
int _type; // 0: A, 1: B
};
void x(P* p)
{
p->f();
}
int main()
{
P *arr[4];
arr[0] = new P(0); // A
arr[1] = new P(1); // B;
arr[2] = new P(1); // B;
arr[3] = new P(2); // P;
for (int i = 0; i < 4; ++i)
x(arr[i]);
cout << endl;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.135.212