指针到指针类型的转换

问题描述 投票:0回答:0

使用继承时,隐式转换允许“方便”的向上转换。例如:

class A{};
class B : public A{};

int main()
{
    B b;
    A* pa = &b; // Implicit conversion from B* to A*
    return 0; 
}

指向指针的指针不一样。例如:

int main()
{
    B* pb = &b;
    B** ppb = &pb;
    
    A** ppa0 = ppb; // cannot initialize a variable of type 'A **' with an lvalue of type 'B **'
    A** ppa1 = &pb; // cannot initialize a variable of type 'A **' with an rvalue of type 'B **'
    A** ppa2 = static_cast<A**>(&pb); // static_cast from 'B **' to 'A **' is not allowed
    A** ppa3 = &static_cast<A*>(pb); // cannot take the address of an rvalue of type 'A *'
    return 0; 
}

最后一个错误让我想到这个行为可能与严格的别名规则有关。另一方面,对于通过基类类型访问值的情况,有一个 豁免。那么为什么不允许

A**
指针保存
B**
指针的地址呢?

c++ pointers c++14
© www.soinside.com 2019 - 2024. All rights reserved.