2011-12-16 116 views
0

我有以下一段代碼。我想知道是否有辦法修改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 
} 

這可能嗎?如果不是,爲什麼?

回答

5

你必須通過引用(或指針,但你不需要指針)參數,否則對象被切片。

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

愚蠢的人性化驗證讓我耽擱了... – 2011-12-16 13:05:11