1.派生類可以重定義(“override(覆蓋)”)基類的非虛函數嗎?合法不合理。有時這樣做是為了更好的利用派生類的資源,即使非虛函數的指派基于指針/引用的靜態類型而不是指針/引用所指對象的動態類型,但其對客戶可見性必須是一致的。
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;
} 這個警告時說派生類f(float)函數和基類的
f(int)同名,派生類的函數隱藏了基類的函數,注意這不是重載(overloaded)或重寫(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,就使用重新定義基類的被隱藏的成員函數,使用::語法調用了基類被隱藏的成員函數
class Derived : public Base {
public:
void f(double x) { Base::f(x); } ← The redefinition merely calls Base::f(double x)
void f(char c);
};
注意:著這不是標準的一部分,所以不是編譯器不一定會出現這個警告。
3.出現連接錯誤"virtual table" is an unresolved external”,意味著類中有一個未定義的虛成員方法。
許多編譯器將“虛表”放進定義類的第一個非內聯虛函數的編輯單元中。因此如果 Fred 類的第一個非內聯虛函數是 wilma(),
那么編譯器會將 Fred 的虛函數表放在 Fred::wilma() 所在的編輯單元里。不幸的是如果你意外的忘了定義 Fred::wilma(),
那么你會得到一個"Fred's virtual table is undefined"(Fred的虛函數表未定義)的錯誤而不是“Fred::wilma() is undefined”(Fred::wilma()未定義)。
4.如何設置使類使用不了繼承:
簡單的方法是將類的構造聲明為私有或使用命名的構造函數(the Named Constructor Idiom),后者可以返回指針如果你想分配對象在堆上(使用new)或返回一個值如果你想分配對象在棧上。
加上注釋也是很很行的方法,例如:// We'll fire you if you inherit from this class or even just /*final*/ class Whatever {...};
最后是使用虛繼承,它可以使派生類的構造直接調用虛基類的構造。例如:下面的代碼可以保證不能從Fred派生類。
class Fred;
class FredBase {
private:
friend class Fred;
FredBase() { }
};
class Fred : private virtual FredBase {
public:
...
}; 如果內存受限制,則要定義一個指針的內存到sizeof(Fred),這是因為大多數的編譯器在實現虛繼承時增加了一個指向派生類的指針。不過這因編譯器而定。