1.派生類可以重定義(“override(覆蓋)”)基類的非虛函數(shù)嗎?合法不合理。有時(shí)這樣做是為了更好的利用派生類的資源,即使非虛函數(shù)的指派基于指針/引用的靜態(tài)類型而不是指針/引用所指對(duì)象的動(dòng)態(tài)類型,但其對(duì)客戶可見(jiàn)性必須是一致的。
2.“
Warning: Derived::f(float) hides Base::f(int)” 意味著什么?
class Base {
public:
void f(double x); ← doesn't matter whether or not this is virtual
};
class Derived : public Base {
public:
void f(char c); ← doesn't matter whether or not this is virtual
};
int main()
{
Derived* d = new Derived();
Base* b = d;
b->f(65.3); ← okay: passes 65.3 to f(double x)
d->f(65.3); ← bizarre: converts 65.3 to a char ('A' if ASCII) and passes it to f(char c); does NOT call f(double x)!!
delete d;
return 0;
} 這個(gè)警告時(shí)說(shuō)派生類f(float)函數(shù)和基類的
f(int)同名,派生類的函數(shù)隱藏了基類的函數(shù),注意這不是重載(overloaded)或重寫(xiě)(overridden)
解決方法:使用using聲明,例如:
class Base {
public:
void f(int);
};
class Derived : public Base {
public:
using Base::f; // This un-hides Base::f(int)
void f(double);
};
如果不支持Using,就使用重新定義基類的被隱藏的成員函數(shù),使用::語(yǔ)法調(diào)用了基類被隱藏的成員函數(shù)
class Derived : public Base {
public:
void f(double x) { Base::f(x); } ← The redefinition merely calls Base::f(double x)
void f(char c);
};
注意:著這不是標(biāo)準(zhǔn)的一部分,所以不是編譯器不一定會(huì)出現(xiàn)這個(gè)警告。
3.出現(xiàn)連接錯(cuò)誤"virtual table" is an unresolved external”,意味著類中有一個(gè)未定義的虛成員方法。
許多編譯器將“虛表”放進(jìn)定義類的第一個(gè)非內(nèi)聯(lián)虛函數(shù)的編輯單元中。因此如果 Fred 類的第一個(gè)非內(nèi)聯(lián)虛函數(shù)是 wilma(),
那么編譯器會(huì)將 Fred 的虛函數(shù)表放在 Fred::wilma() 所在的編輯單元里。不幸的是如果你意外的忘了定義 Fred::wilma(),
那么你會(huì)得到一個(gè)"Fred's virtual table is undefined"(Fred的虛函數(shù)表未定義)的錯(cuò)誤而不是“Fred::wilma() is undefined”(Fred::wilma()未定義)。
4.如何設(shè)置使類使用不了繼承:
簡(jiǎn)單的方法是將類的構(gòu)造聲明為私有或使用命名的構(gòu)造函數(shù)(the Named Constructor Idiom),后者可以返回指針如果你想分配對(duì)象在堆上(使用new)或返回一個(gè)值如果你想分配對(duì)象在棧上。
加上注釋也是很很行的方法,例如:// We'll fire you if you inherit from this class or even just /*final*/ class Whatever {...};
最后是使用虛繼承,它可以使派生類的構(gòu)造直接調(diào)用虛基類的構(gòu)造。例如:下面的代碼可以保證不能從Fred派生類。
class Fred;
class FredBase {
private:
friend class Fred;
FredBase() { }
};
class Fred : private virtual FredBase {
public:
...
}; 如果內(nèi)存受限制,則要定義一個(gè)指針的內(nèi)存到sizeof(Fred),這是因?yàn)榇蠖鄶?shù)的編譯器在實(shí)現(xiàn)虛繼承時(shí)增加了一個(gè)指向派生類的指針。不過(guò)這因編譯器而定。