跳至主要內容

继承中的类型转换

张威大约 2 分钟c/c++继承

继承中的类型转换

image-20240414114736980
image-20240414114736980

派生类适应于基类,派生类的对象适应于基类对象,派生类对象的指针和引用也适应于基类对象的指针和引用

  • 可以把给基类的对象
  • 可以把绑定到派生类的对象(只能访问基类的部分)
  • 可以声明指向派生类的对象 (向上转型)(解引用只能访问基类的部分)

也就是说如果函数的对象或者基类对象的引用或者基类对象的指针类型,在进行函数调用时,相应的

class Base
{
public:
    Base(long base)
    {   
        cout << "Base(long)" << endl;   
    }
private:
    long _base;
};
class Derived
: public Base 
{
public:
    Derived(long base, long derived)
    : Base(base)
    , _derived(derived)
    {   
        cout << "Derived(long,long)" << endl;   
    }
private:
    long _derived;
};
void test() 
{
    Base base(1);
    Derived derived(10, 11);
    
    base = derived;//ok
    Base &refBase = derived;//ok
    Base *pBase = &derived;//ok
    derived = base;//error
    Derived &refDerived = base;//error
    Derived *pDerived = &base;//error
    
    cout << endl << endl;
    Base base2(10);
    Derived derived2(20, 30);
    
    Derived *pderived2 = static_cast<Derived *>(&base2);//不安全的向下转型
    pderived2->print();
    cout << endl;
    Base *pbase3 = &derived2;
    Derived *pderived3 = static_cast<Derived *>(pbase3);//安全的向下转型
    pderived3->print();
}

在继承结构中进行上下的类型转换,默认只支持从下到上的类型的转换。除非进行强转,但强转会涉及内存的

[类型转换函数 | 张威的编程学习笔记 (gitee.io)](https://iszhwei.gitee.io/ccpp/02 c__基础/强制转换.html#static-cast)