Loading

MoreEffect[3] 不要对数组使用多态

不要对数组使用多态

数组中每个元素的内存间隔是sizeof(type),数组下标索引根据数据类型的大小做偏移array + index * sizeof(type)。这要求编译器明确数组对象类型的大小。

但在多态中,基类指针或引用的实际类型是不明确的,编译器没法确定数组每个元素的间隔

C++允许通过基类指针和引用来操作派生类数组,但__编译器会假设数组类型内存大小为基类的内存大小,不会考虑多态的情况__。而派生类的内存通常要比基类大,因此可能发生难以察觉的错误。

代码验证

class baseClass
{
public:
    int val;// 1
    baseClass(void) : val(1) {};   
};

class childClass : public baseClass
{
    int expandVal;// 2
public:
    childClass(void) : expandVal(2) {};
};

void loopFunc(int size, baseClass array[])
{
    for(int i=0; i<size; ++i)
    {
        cout << array[i].val << endl;
    }
}

int main(void)
{
    baseClass  baseArray[3];
    childClass childArray[3];
    
    //base
    cout << "base loop" << endl;
    loopFunc(3, baseArray);

    //base
    cout << "child loop" << endl;
    loopFunc(3, childArray);

    return 0;
}
#output
base loop
1
1
1
child loop
1
2
1

可见,在遍历派生类数组时的输出并不是期望的值,应尽量避免使用基类指针或引用对派生类数组操作。

posted @ 2021-08-01 23:37  sandersunkown  阅读(61)  评论(0)    收藏  举报