多重和虚拟继承的类型转换

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

为什么虚拟继承编译

static_pointer_cast
时出错?

#include <iostream>
#include <memory>

struct Top {
    int a = 1;
};

struct Left : public Top {
    int b = 2;
};

struct Right : public Top {
    int c = 3;
};

struct Bottom : public Left, public Right {
    int d = 4;
};

int main() {
    std::shared_ptr<Right> pright = std::make_shared<Bottom>();
    std::shared_ptr<Top> ptop = pright;
    auto p = std::static_pointer_cast<Right>(ptop); // work well
    std::cout << "c: " << p->c << std::endl;
}

链接

static_pointer_cast
适用于多重继承。

#include <iostream>
#include <memory>

struct Top {
    int a = 1;
};

struct Left : virtual public Top {
    int b = 2;
};

struct Right : virtual public Top {
    int c = 3;
};

struct Bottom : public Left, public Right {
    int d = 4;
};

int main() {
    std::shared_ptr<Right> pright = std::make_shared<Bottom>();
    std::shared_ptr<Top> ptop = pright;
    auto p = std::static_pointer_cast<Right>(ptop); // compile error!
    std::cout << "c: " << p->c << std::endl;
}

链接

为什么虚拟继承编译

static_pointer_cast
时出错?

c++11 multiple-inheritance static-cast virtual-inheritance
© www.soinside.com 2019 - 2024. All rights reserved.