我觀看了一個視頻,可以在 https://www.youtube.com/watch?v=4F72VULWFvc找到,我真的很喜歡這個案例的一些概念。但我用鏈表的工作,需要選擇性的方法執行,例如:繼承,選擇性執行方法
#include <stdio.h>
class A {
public:
A() : next(0) {
if (head == 0) {
head = this;
} else {
A* step = head;
while (step->next != 0) {
step = step->next;
}
step->next = this;
}
}
virtual ~A() {
if (head == this) {
head = 0;
} else {
A* step = head;
while (step->next != this) {
step = step->next;
}
step->next = next;
}
}
virtual void foo() {
// Do nothing...
}
static A* head;
A* next;
};
class B : public A {
public:
B() {}
virtual ~B() {}
virtual void foo() {
printf("function foo\n");
}
};
A* A::head = 0;
int main() {
A a_cls;
B b_cls;
A* step = A::head;
while (step != 0) {
step->foo();
step = step->next;
}
return 0;
}
實例的所有對象後,B
類的對象的方法foo()
需要執行。爲了實現這一點,虛擬方法foo()
被添加到類A,具有空主體virtual void foo() {}
,並且在類B中,代碼被添加到方法foo()
正文。
它的工作原理,但我不喜歡它,在主函數中,它看起來像你在每個節點上做的事情,但你不是,它幾乎感覺像一個NULL指針。有沒有另一個創造性的解決方案呢?
注意:我正在使用C++ 03。
致OP:請理解這是脆弱的代碼。只要將'C'類型引入'A'的子類型,就需要另一個'if'子句。這正是使用多態的原因。 –
我想我需要了解更多OP的意圖,以瞭解我是否同意這一說法。如果C源自B,則不需要額外的if語句。如果我們想爲C調用一個不同於B的方法,那麼不管我們需要一個if語句。 –