函数参数,多态性
问题描述:
我有以下一段代码。我想知道是否有办法修改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
}
这可能吗?如果不是,为什么?
答
你必须通过引用(或指针,但你不需要指针)参数,否则对象被切片。
void foo(A& a) { a.print(); }
愚蠢的人性化验证让我耽搁了... – 2011-12-16 13:05:11