【发布时间】:2017-08-27 13:00:53
【问题描述】:
我这里什么都不懂。我希望如果我可以将 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** 一样,那将是一种向上转换,不是吗?
【问题讨论】:
-
interconvertible 指针类型是指向派生/基类型对象的指针。指向指针的指针不能与其他类型相互转换。同样适用于引用。
-
如果你可以做
ptrToPtr,你可以做*arg = new Cat;和dog将不再指向Dog。
标签: c++ pointers inheritance upcasting