簡體   English   中英

C++ 中的多態性:我是否必須給孩子 class 功能與父母相同的 arguments - 如何重載

[英]Polymorphism in C++: Do I have to give child class functions the same arguments as the parents - how to overload

如果我有這樣的父母 class :

class Parent {
protected:
   virtual void foo(type1 var1, type2 var2);
}

和一個孩子 class:

class Child : public Parent {
   foo(type1 var1, type2 var2);
}

但是如果Child中的foo function 不需要var1var2怎么辦? 有沒有辦法告訴編譯器不要給這些變量 memory 因為它們沒有被使用? 或者,你如何超載它? 雖然結合了重載和多態......你是怎么做到的(如果你可以/願意的話。)。

謝謝你。

如果孩子的 function 簽名與對方的簽名不同,那么孩子有兩個函數被重載

編譯器會根據你給它的 arguments 選擇正確的。 如果願意,可以修改其 arguments 並將工作轉發給另一個 function。

例如,

class Child : public Parent {
   using Parent :: foo;
   void foo (type1 var1);
};

Child c;
child .foo (type1()); // Valid
child .foo (type1(), type2()); // Valid, calls Parent::foo

void Child :: foo (type1 x) {
    Parent :: foo (x+1, blah);
}

或者,如果您想消除歧義。

class Child : public Parent {
   void foo (type1 var1, type2 var2);
};

Child c;
child .foo (type1(), type2()); // Valid, calls Child::foo
child .Parent :: foo (type1(), type2()); // Valid.

覆蓋是另一回事。

class Parent {
    virtual void foo () {}
};

class Child1 : parent {
    void foo ();
};

class Child2 : parent {
    void foo ();
};

void call_foo (Parent & p) {p .foo ();}

Parent p;
Child1 c1;
Child2 c2;
call_foo (p); // Calls Parent::foo
foo (c1);     // Calls Child1::foo
foo (c2);     // Calls Child1::foo

您只需在 Child class 中使用不同的簽名(即不同的參數)定義另一個 foo function 。 這是重載function foo。 編譯器會根據你輸入的參數執行正確的function。

暫無
暫無

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

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