簡體   English   中英

指向基類的指針作為重載函數的參數

[英]Pointer to base-class as argument of an overloaded function

我有以下幾點:

class Base {};
class Derived : public Base {};

void foo(Base const &b) { cout << "foo(Base)" << endl; }
void foo(Derived const &d) { cout << "foo(Derived)" << endl; }

/* ... */

Base *bb = new Base();
Base *bd = new Derived();
Derived *dd = new Derived();

foo(*bb);
foo(*bd); // <== calling foo(Base const &)
foo(*dd);

程序輸出foo(Base),foo(Base)和foo(Derived)。 為什么第二次調用foo(Base) 我該如何重寫它,以第二次調用foo(Derived) 謝謝!

當用*bdfoo()時, bdBase* ,就像定義它一樣:

  • Base *bd =...

因此,編譯器將調用void foo(Base const&)

如果確定可以進行向下轉換,則可以調用static_cast<>()

  • foo( * static_cast<Derived*>(bd) );

我覺得那很丑。

您可以簡單地使用覆蓋。

struct Base
{
    virtual void foo(){ std::cout << "only base and derived classes that don't overide foo"; }
    virtual ~Base(){};
};

struct MyDerived : public Base
{
    virtual void foo(){ std::cout << "only MyDerived calls this function"; }
};

void test()
{
    Base b;
    MyDerived d;

    b.foo(); // prints: only base and derived that don't overide foo
    d.foo(); // prints: only MyDerived calls this function
}

在重載解析中, Base對於notBase&Base&更好。

您似乎想要多態行為,因此必須通過至少包含一個虛函數來使您的類多態。 (這可能是析構函數)。

多態也不影響重載分辨率。 要獲得多態行為,您必須通過virtual函數或dynamic_cast

一種選擇(不是很好,但是有可能)是用以下方法打開foo

void foo(Base const &b)
{
    Derived const *d = dynamic_cast<Derived const *>(&b);
    if ( d ) { foo(*d); return; }

由R Sahu鏈接到的引擎是對此的概括,您在其中注冊了各種派生類,以避免產生大量的copypasta。

但是,使用虛函數被認為是更好的樣式。 如果您不想將foo更改為只是一個多態調用Base函數,那么一種實現方法是:

void foo(struct Base const &b);
void foo(struct Derived const &d);

struct Base
{
    virtual void foo_caller() const { foo(*this); }
    // ...
};

struct Derived
{
    virtual void foo_caller() const { foo(*this); }
    // ...
};

int main()
{
    Base *p = new Derived();
    p->foo_caller();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM