请考虑以下代码:
class A { public: virtual ~A() { } virtual void print() const { std::cout << "In A" << std::endl; } }; class B : public A { public: B() { } virtual ~B() { } virtual void print() const { std::cout << "In B" << std::endl; } }; void doSomething(A* a) { a->print(); } void doSomething(const A a) { a.print(); } int main() { A* a = new B(); doSomething(a); doSomething(B()); return 0; }
为什么这个输出:
In B In A
但当你改变doSomething to doSomething(const A& a)时,它会输出:
In B In B