基类与指针、向上映射





// 函数体里的内容在栈区
//static 声明的在堆区

#include <iostream>

using namespace std;




// 继承与指针,向上映射,派生类与基类的交集

//向上转型后,基类指针只能访问「继承自基类的成员」(这就是两者的交集),无法访问派生类独有的成员。



// 基类:矩形
class Rectangle {
public:
    // 带参构造函数
    Rectangle(int len, int wid);
    // 非虚函数 → 静态绑定
    void show();

// 私有成员:派生类不能直接访问,但会被继承
private:
    int length, width;
};

// 派生类:公有继承矩形
class B : public Rectangle {
public:
    // 派生类构造:必须显式调用基类构造函数
    B(int len, int wid);
    // 重写基类的show
    void show();
};

// 基类构造函数:初始化列表初始化所有成员(规范写法)
Rectangle::Rectangle(int len, int wid) : length(len), width(wid) {}

// 基类show:打印长度
void Rectangle::show() {
    cout << "基类Rectangle::show() → length = " << length << endl;
}

// 派生类构造:必须先调用基类构造!!!
B::B(int len, int wid) : Rectangle(len, wid) {}

// 派生类show
void B::show() {
    cout << "派生类B::show() → length = " << length << endl;
}

int main() {
    Rectangle a(1, 2);
    B b(3, 4);
    Rectangle* p; // 基类指针

    p = &a;  // 指针指向基类对象
    p->show(); // 调用基类show

    p = &b;  // 向上转型:基类指针指向派生类对象
    p->show(); // 无多态 → 依然调用基类show

    return 0;
}

 

运行结果

posted @ 2026-04-19 09:17  叶臧  阅读(13)  评论(0)    收藏  举报