想象一下这段代码:
class Base {
public:
virtual void foo(){}
};
class Derived: public Base {
public:
int i;
void foo() override {}
void do_derived() {
std::cout << i;
}
};
int main(){
Base *ptr = new Base;
Derived * static_ptr = static_cast<Derived*>(ptr);
static_ptr->i = 10; // Why does this work?
static_ptr->foo(); // Why does this work?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我在控制台上获得结果10?我想知道因为我认为ptr是指向基础对象的指针.因此,该对象不包含int i或方法do_derived().是否自动生成了一个新的derived-Object?
当我do_derived()在Base类中声明一个虚方法时,会选择这个,但为什么呢?
为什么容器适配器喜欢std::stack或std::queue实现为适配器而不是独立容器?是因为你想要一个具有不同序列容器的底层内存管理的堆栈?
为什么STL的算法实现为自由函数,它们期望迭代器,而不是相应容器的方法?