函数参数,多态性

Zav*_*ior 0 c++

我有以下代码.我想知道是否有办法修改foo(A a),以便调用它将得到如下面注释代码中的结果,但没有重载.

class A { 
  public: virtual void print() { std::cout << "A\n"; } };
class B : public A {
  public: virtual void print() { std:cout << "B\n"; }
};

void foo( A a ) { a.print(); } // How to modify this, so it chooses to use B's print()?
// void foo( B a ) { a.print(); } // now, this would work! 

int main( void ) { 
  A a; 
  foo( a ); // prints A
  B b;
  foo(b);  // prints A, but I want it to print B
}
Run Code Online (Sandbox Code Playgroud)

这有可能吗?如果没有,为什么?

Cat*_*lus 5

你必须通过引用(或指针,但你不需要指针)来获取参数,否则对象会被切片.

void foo(A& a) { a.print(); }
Run Code Online (Sandbox Code Playgroud)