2009-09-04 50 views
1

有人可以解釋爲什麼下面的代碼無效嗎?是否因爲名爲d的變量的偏移量與名爲b的變量不同?調用函數並將參考指針傳遞給派生類型時出錯

class Base { public: int foo; }; 

class Derived : public Base { public: int bar; }; 

int DoSomething(Base*& b) { return b->foo; } 

Base* b = new Derived; 
Derived* d = new Derived; 

int main() 
{ 
    DoSomething(d); 
} 

這是錯誤the online Comeau C++ compiler給出:

"ComeauTest.c", line 12: error: a reference of type "Base *&" (not const-qualified) 
      cannot be initialized with a value of type "Derived *" 
    DoSomething(d); 
       ^

這是一個類似的問題,但不同的是,因爲在我的例子,我聲明d爲指針類型:Passing references to pointers in C++

注當我通過bDoSomething時,這確實會編譯。

回答

10

想象一下,你可以做到這一點。引用不是const,所以可以將DoSomething分配給指針,並且在調用者中可見。特別是,在DoSomething內部,我們可以將指針改爲指向不是Derived實例的東西。如果調用者在我們返回之後嘗試對指針執行派生特定的事情,它將會爆炸。

3

這與偏移無關。請注意,Derived在您的示例中既有foo也有bar作爲字段(並且是的,它們將具有不同的偏移量,但這與此無關)。

如果允許這樣做,它將不會是類型安全的。考慮以下代碼:

class Base { public: int foo; }; 

class Derived1 : public Base { public: int bar; }; 

class Derived2 : public Base { public: float baz; }; 

void DoSomething(Base*& b) { b = new Derived2; } 

Derived1* d = new Derived1; 
DoSomething(d); // d is of type Derived1*, but now points to object 
       // of incompatible type Derived2 
3

假設DoSomething的是這樣定義的:

int DoSomething(Base*& b) { b = new Base; } 

哎呀,現在主要在調用DoSomething的,d結束在基本指向,而不是在所有派生。

相關問題