函数参数,多态

function parameters, polymorphism

本文关键字:多态 参数 函数      更新时间:2023-10-16

我有以下一段代码。我想知道是否有一种方法来修改foo(a a),以便调用它会产生如下面的注释代码中的结果,但没有重载。

class A { 
  public: virtual void print() { std::cout << "An"; } };
class B : public A {
  public: virtual void print() { std:cout << "Bn"; }
};
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
}

这可能吗?如果不是,为什么?

必须通过引用(或指针,但这里不需要指针)接受实参,否则对象将被切片。

void foo(A& a) { a.print(); }