考慮下面的代碼:衍生**基地**
#include <iostream>
using namespace std;
class Base
{
public:
int foo;
};
class Derived : public Base
{
public:
float bar;
};
int main()
{
Base** baseArr = new Base*[30];
for (int i=0; i<30; i++)
{
Derived* derived = new Derived();
derived->foo = i;
derived->bar = i * 2.5;
baseArr[i] = derived;
}
//Notice this!
Derived** derivedArr = (Derived**)(baseArr);
for (int i=0; i<30; i++)
cout << "My Base " << i << ": " << derivedArr[i]->foo << ", " << derivedArr[i]->bar << endl;
return 0;
}
它是安全的這樣做數組的數組類型轉換?整個程序的指針大小是一樣的,所以聽起來好像我不會得到任何填充錯誤。但是,我知道正確的方法是遍歷每個元素並單獨投射。
然而,我試着去利用這種投將我的模板公共職能的實現使用非通用私有函數返回數組.cpp文件,所以我可以肯定,我的Base
數組將只包含特定Derived
指針。
private:
Base** Find(function<bool(Base*)> Predicate, int& N); //Implemented in .CPP
public:
template <class T> T** FindByType(int &N) //T is derived from Base
{
//Safe?
return (T**)(Find(
[](Base* b)->bool { return typeid(T) == typeid(b); },
N));
};
這當然只是一個簡單的例子。在這種情況下,我有很多理由使用RTTI。 N用於控制數組大小。
我想知道如果這個不安全投將與多繼承失敗,例如像Derived
類也將繼承OtherBase
,我想投給OtherBase**
,我也想知道如果任何機會,我到達未定義的行爲,或者我決定使用這種構造時可能遇到的任何潛在問題。
您應該使用標準的[容器](http://en.cppreference.com/w/cpp/container),例如[std :: vector](http://en.cppreference.com/w/cpp/container/vector) –
不,這是不安全的,指針別名說不。 –
@BasileStarynkevitch,你可以安全地施放矢量到矢量沒有for循環? –