讓我們舉一個例子:是否推薦使用向下轉換來設置派生類成員變量?
class Parent{
}
class Derived1:public Parent{
public:
int x;
}
class Derived2:public Parent{
public:
int y;
}
main()
{
int i;
std::cin >> i;
Parent *p;
switch(i)
{
case 0:
p = new Derived1()
static_cast<Derived1>(p)-> x = 1;
break;
case 1:
p = new Derived2()
static_cast<Derived2>(p)-> y = 2;
break;
}
process(*p);
}
是向下投射來設置派生類的成員變量推薦的做法?有沒有比上述更清潔的替代品?
爲什麼不將成員的初始值傳遞給構造函數? – Brian 2014-09-01 05:21:31
不應該是'process(p)',而不是'process(* p)'? – justanothercoder 2014-09-01 05:23:47
@Brian,當然,我當然可以,只是在我的實際代碼中,我確定了Derived類的值,我不想保留臨時變量arround – Kam 2014-09-01 05:26:36