關於1和2,因爲foo是不可見有一個錯誤(和A::foo
還沒有一個機構):
class B : public A{
int var;
void foo();
};
無論如何,因爲你不通過指針/引用調用它
void func(){
B myObj;
myObj.foo(); // No polymorphic behavior here, B::foo is called
myObj.bar(); // the same, but A::bar is called since B hasn't one
}
關於3.和4。如果基類和派生類都有一個具有相同名稱的變量,則派生類將隱藏基類的名稱,並且通過派生對象的每次訪問都將導致派生類被設置/調用(除非明確執行base::var
)。如果只有一個擁有它,那就沒問題,他們都會調用相同的版本(只要它是可見/可訪問的)。在你上面的例子:
void A::bar(){
std::cout << var; // This will output an uninitialized A::var!
}
void B::foo(){
var = 42; // B's var hides A's var so this only sets the derived one's
}
編輯:爲A2
和B2
的情況下還有的A2::var
只有一個實例,每個訪問它,甚至從一個派生類中,將參考基地之一,例如
class A2{
virtual void foo() = 0;
public:
int var;
void bar() {
std::cout << var; // Will correctly output 42
}
};
class B2 : public A2{
public:
void foo() {
var = 42; // Sets the common A2::var variable
};
};
void func2(){
B2 myObj;
myObj.foo();
myObj.bar();
}
看一看,研究以下內容:Example
您是否嘗試過簡單地運行代碼以找出答案?在我看來,如果你可以運行並嘗試這個? – MrHug 2014-10-20 14:07:00
我想了解爲什麼有些事情可行,爲什麼不行。當然,我也會運行它。 – tMJ 2014-10-20 14:08:39
'func'不會編譯:'myObj.foo'是私有的。 – aschepler 2014-10-20 14:10:22