我有以下代码:
#include <string>
#include <iostream>
class A{
public:
virtual void print() {std::cout << "A" << std::endl;};
};
class B : public A{
public:
void print() {std::cout << "B" << std::endl;};
};
int main(){
A* a1;
a1 = new B;
B b;
A a2 = b;
a1->print();
a2.print();
std::string s2;
std::getline (std::cin,s2);
}
它产生的输出是
B
A
现在,为什么在对象是指针时调用派生方法,在对象不是时调用基本方法?