[英]How to Correct the Polymorphism
我有以下代碼。
#include <iostream>
class Base1
{
public:
void print(){std::cout<<"Printing Base1\n";}
};
class Derived1: public Base1
{
public:
void print_1(){std::cout<<"Printing Derived1 \n";}
};
class Base2
{
public:
void myFunction1( Base1& b1)
{
myFunction2(b1);
}
virtual void myFunction2( Base1& b1)
{
b1.print();
}
};
class Derived2: public Base2
{
public:
void myFunction2( Derived1& d1)
{
d1.print_1();
}
};
int main()
{
Base1 b1;
Derived1 d1;
Base2 b2;
Derived2 d2;
b2.myFunction1(b1);
d2.myFunction1(d1);
return 0;
}
結果如下:
Printing Base1
Printing Base1
我想到了以下輸出
Printing Base1
Printing Derived1
獲得所需輸出的一種方法是執行以下操作。
class Derived2: public Base2
{
public:
void myFunction2( Base1& b1)
{
Derived1* d1 = static_cast<Derived1*> (&b1);
d1.print_1();
}
};
我想允許Derived2僅處理Derived1,而不處理Base1。 否則,某些用戶可能會使用Base1對象調用Derived2 :: myFunction2,這可能會使程序崩潰。
有沒有好的解決方案?
myFunction2()
在Derived2
不覆蓋myFunction2()
在Base2
。
虛擬函數僅在其簽名完全匹配時才被覆蓋。 此派生類中的函數采用與基類中不同的參數。 因此,它不會覆蓋。
第一步,必須使其覆蓋。
class Derived2: public Base2
{
public:
void myFunction2( Base1& d1) override;
};
現在已被覆蓋。 如果像我在這里那樣明確指定了override
限定符,則編譯器已經對您大喊大叫。
現在,您的目標是擁有myFunction2
所做的一切,僅使其對Derived1
類生效,對於所有其他Base1
類,使用超類所做的事情。
好。 這將需要更多的工作,並且后續操作會有些困難。 需要發生的是這次在Base1
另一個虛擬繼承:
class Derived2: public Base2
{
public:
void myFunction2( Base1& d1) override
{
d1.print_from_Derived2( *this );
}
};
現在,您需要定義Base1::printDerived2()
,它將調用print()
,這是在這種情況下根據您的問題而發生的情況:
class Base1
{
public:
virtual void print_from_Derived2( Derived2 &)
{
print();
}
};
現在,在Derived1
中覆蓋它,以便將拼圖的最后一部分放在一起:
class Derived1 : public Base1
{
public:
void print_from_Derived2( Derived2 &) override
{
// Do whatever print() from Derived2 needs to do, for
// this object, which is Derived1.
}
};
在這里,您將完成Derived2
只打印Derived1
。 這是一條circuit回曲折的路線,但是您最終到達了兩個參與者都是Derived1
和Derived2
,沒有違反任何規則,也沒有任何丑陋的演員。
您將需要在此處做一堆前向聲明,以便將所有這些可移動的部分縫合在一起。 我的示例只是簡單的簡化,它們顯然相互引用,並且必須分解為單獨的聲明和定義以及適當的前向聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.