使用void指针分配对象数组

时间:2015-04-13 17:26:05

标签: c++ pointers dynamic void allocation

我正在尝试分配不同数据类型的数组,在运行时决定。请考虑以下内容,请原谅格式:

#include <iostream>

unsigned int Wlines;

class Cache_X_line          //Datatype1
{   public:
    unsigned int Tag;
};

class Cache_Y_line         //Datatype2
{   public:
    unsigned int lob;
};

class Cache_set
{   private:
    unsigned int i;

    public:
    void **line;                                //Using void pointer

    Cache_set(bool linetype)
    {   if(Wlines!=0)
            line= new void * [Wlines];          //array of void pointers

        for(i=0;i<Wlines;i++)
        {   if(linetype)
                line[i]=new Cache_X_line;       //allocating objects of datatype1 

            else
                line[i]=new Cache_Y_line;       //allocating objects of datatype2
        }
    }
};

int main()

{   cout<<"Enter Wlines:";
    cin>>Wlines;

    Cache_set Set(1);               //Object having member that is allocated array of datatype1.

    clog<<hex<<Set.((Cache_X_line *)line[i])->Tag;  //PROBLEM: UNABLE TO TYPECAST, to access members of allocated object.

}

我能够分配datatype1 / datatype2的对象数组,在运行时决定数据类型。但我不知道如何进一步访问每个对象的成员。请帮忙。

1 个答案:

答案 0 :(得分:3)

  

我能够分配datatype1 / datatype2的对象数组,在运行时决定数据类型。但我不知道如何进一步访问每个对象的成员。

我的建议:

  1. 创建一个公共基类,Cache_X_LineCache_Y_Line可以从中派生。确保基类至少有一个虚函数。在其他方面都无法虚拟化,使析构函数变为虚拟。

  2. void*中存储指向基类的指针,而不是Cache_Set。最好存储一个std::vector智能指针,而不是存储原始指针。

  3. 使用指针时,请执行dynamic_cast。当dynamic_cast成功派生类型时,使用派生类型。

相关问题