class Base1{
public:
Base1(){};
virtual ~Base1() = 0;
}
class Derived1 : public Base1{
public:
Derived1(int a) : a(a){};
~Derived1();
int a;
}
class Base2{
public:
Base2(){};
virtual ~Base2() = 0;
}
class Derived2 : public Base2{
public:
Derived2(int b) : b(b){};
~Derived2();
int b;
void func(const Base1 &base1); // How to access Derived1::a here?
}
Derived1::a鑒于上述類定義,我如何訪問void func(const Base1 &base1)?我對多型性仍然很陌生。我嘗試使用不同的 static_cast 或 dynamic_cast 方法,但它們都不起作用。我應該在函式內部做什么才能從基類參考訪問派生類成員?
僅供參考,我無法更改課程要求的課程定義,這就是給我的。我知道將 Derived1 作為引數傳遞更簡單,但我不允許這樣做。
uj5u.com熱心網友回復:
Derived1::a鑒于上述類定義,我如何訪問void func(const Base1 &base1)?...僅供參考,我無法更改課程要求的課程定義,這就是給我的。
理想情況下,您應該公開一個回傳(or ) 的virtual方法,然后重寫該方法以回傳其成員。Base1intint&Derived1a
但是,鑒于您不允許更改類定義,這不是一個選項。
您需要指向Derived1物件的指標或參考才能直接訪問其a成員。這真的讓您只有 1 個選擇 - 您可以使用dynamic_cast將基類參考型別轉換為派生型別別,例如:
void Derived2::func(const Base1 &base1)
{
// this will raise an exception if the cast fails at runtime
const Derived1 &d = dynamic_cast<const Derived1&>(base1);
// use d.a as needed...
}
或者:
void Derived2::func(const Base1 &base1)
{
// this will return null if the cast fails at runtime
const Derived1 *d = dynamic_cast<const Derived1*>(&base1);
if (d) {
// use d->a as needed...
} else {
// do something else...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448840.html
上一篇:沒有顯式特化宣告的顯式模板特化
下一篇:在符號表中如何標記變數超出范圍?
