簡體   English   中英

無法將指針向上轉換為指針參數

[英]Can't upcast pointer to pointer argument

我在這里什么都不懂。 我希望,如果我可以將dog指針傳遞給采用動物指針的函數,也可以將&dog傳遞給采用指向Animal指針的函數。

struct Animal{};
struct Dog : Animal{};

void ptrToPtr(Animal** arg){}
void refToPtr(Animal*& arg){}
void refToConstPtr(Animal* const & arg){}
void ptrToConstPtr(Animal* const * arg){}

int main(void)
{
    Dog* dog;
    Animal* animal;

    ptrToPtr(&animal); // Works
    ptrToPtr(&dog); // Argument of type Dog** is incompatible with argument of type Animal**

    refToPtr(animal); // Works
    refToPtr(dog);      // A reference of type Animal*& (not const-qualified) cannot be initialized with a value of type Dog*

    ptrToConstPtr(&animal); // Works
    ptrToConstPtr(&dog);    // Argument of type Dog** is incompatible with paramater of type Animal* const*

    refToConstPtr(animal); // Works
    refToConstPtr(dog);  // Works. This is the only one that allows me to send Dog to Animal

    return 0;
}

我只是不明白,有誰能解釋為什么特定案例起作用而其他案例不起作用的原因是什么? 就像將狗的指針地址傳遞給Animal **一樣,這是一個錯誤,不是嗎?

互轉換指針類型是指向派生/基本類型的對象的指針。 A“指針的指針”是不是相互轉換的與其它類型的(具有除外void* )。 同樣適用於參考文獻。

這意味着給定以下任何層次結構:

struct Animal{};
struct Dog : Animal{};

和以下變量:

Dog* dptr;
Animal* aptr;

dptr可以轉換為Animal* (甚至隱式),同樣aptr可以轉換為Dog* (但不能隱式)。 因為:在類層次結構中進行向上轉換始終是合法的,因此這將由ICS隱式完成。 但是,向下轉換並不總是這樣,因此它從未隱式完成)

然而:

Dog** ddptr;
Animal** aaptr;

ddptr不能隱式轉換為Animal** ,同樣aptr不能轉換為Dog** 因為,它們是兩種沒有層次關系的不同類型。




上面的解釋說明了為什么指針重載指針失敗。 也就是說,讓我們處理引用類型的重載。 根據您的代碼,

refToPtr(animal); // Works
refToPtr(dog);      // A reference of type Animal*& (not const-qualified) cannot be initialized with a value of type Dog*

第二個調用不起作用,因為說X非常量引用只能綁定到X的確切glvalue對象。 由於refToPtrAnimal*類型采用非常量引用,因此我們只能向其傳遞Animal*類型的glvalues,即animal是,而dog不是。

最后一個有效,這是合法的,因為

refToConstPtr(animal); // Works
refToConstPtr(dog);    // Works. This is the only one that allows me to send Dog to Animal

const發言權引用X可以綁定到任何值產品類別X ,包括temproaries其壽命延伸。 因為我們可以將dog轉換為Animal* 進行該轉換並生成一個臨時的Animal* ,其壽命通過const引用延長。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM