为什么虚拟继承编译
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
时出错?