[英]C++: Accessing variables present only in one of the derived classes
void func1()
{
}
class Base
{
public:
virtual void memfunc() = 0;
};
class DerivedA: public Base
{
public:
virtual void memfunc() = 0;
};
class Derived1: public DerivedA
{
public:
void memfunc()
{
func1();
}
};
class Derived2: public DerivedA
{
public:
int* pbuf;
int val;
void func2(int* pbuf,int val)
{
/* update pbuf depending on the value of val*/
}
void memfunc()
{
func1();
func2(pbuf,val);
}
};
class user{
public:
Base* mBase;
void userfunc()
{
mBase = f(); //Object pointer to Derived1/Derived2 will be assigned based on dynamic loading;
//Before calling the below func, I Need to assign value to the 'val' variable of the class 'Derived2'
mBase->memfunc();
}
};
int main()
{
user ouser;
ouser.userfunc();
return 0;
}
變量val
和pbuf
僅存在於Derived2
。 我不知道對象mBase
是否指向Derived1/Derived2
, Derived1/Derived2
如何在userfunc/main
為其分配值。
您可以使用dynamic_cast並檢查NULL,如果對象的類型不是Derived2,則將返回NULL。 如果強制轉換成功,則可以使用Derived2的所有方法。
在userfunc()
使用dynamic_cast
並測試Derived2
,即
Derived2* p = dynamic_cast<Derived2*>(mBase);
if (p) // this is NULL if the above fails.
{
// initialize...
}
如果val和pbuf僅存在於Derived2上,那么您必須有某種方法來識別它們。 您將需要創建一個枚舉Base :: Type {Derived1,Derived2},將它們設置在派生類上,然后在main中進行測試。 然后,可以將mBase轉換為Derived2(如果具有該類型),並設置val。
如果您確定類的具體類型,則可以使用dynamic_cast。 無論如何,這是一個壞習慣。 使用基本抽象類引用的目的是隱藏內部細節和特定的實現問題。
如果需要這樣做,也許可以將getProperty()/ setProperty()方法添加到基類中。 就像是:
class Base
{
public:
virtual void memfunc() = 0;
virtual void setProperty(String name, Property prop);
virtual Property getProperty(String name);
};
使用typeid:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.