C ++:我可以在void函数中实例化一个对象吗?

时间:2018-04-06 03:20:50

标签: c++ pointers reference

出于我正在制作的节目的目的,我试图做这样的事情:

void instantiate(myType t){

   t = new myType();

}

int main(){

   myType* t = NULL;

   .
   .
   .

   instantiate(t);

   .
   .
   .

   if (t != NULL){
      do something;
   }
}

然而,任何了解C ++的人都知道,在退出该函数的范围之后,t将继续为NULL。但有没有办法按我的意愿做这项工作?为了清楚起见,它必须是一个void函数(不能像" t = instantiate()"),因为它将用于在同一函数中实例化多于一种类型的类

编辑:songyuanyao的评论解决了我的问题,但是由于评论中的人建议如果我提供更多关于我的场景的详细信息,可能会有更好的解决方案,这里是:

void instantiateHash(Ohash*& OH, Chash*& CH, HOhash*& HOH, int type, int size, int limit){

    if (type == 1){
        OH = new Ohash(size, type);
    }else if (type == 2){
        CH = new Chash(size, type);
    }else{
        HOH = new HOhash(size, limit);
    }
}

void insertIntoHash(Ohash*& OH, Chash*& CH, HOhash*& HOH, string s){

    //The functions for operations in the hashtables are different for each type
    if (OH != NULL){
        OH->insert(s);
    }else if (CH != NULL){
        CH->insert(s, CH->table, CH->size);
    }else{
        HOH->insert(s, CH->table, CH->limit);
    }

}

void mainMenu(int t, int s, int l){

    Ohash* OH   = NULL;
    Chash* CH   = NULL;
    HOhash* HOH = NULL;
    string str;    

    //Instantiates a particular type of hashtable according to the type variable
    instanciateHash(OH, CH, HOH, t, s, l);

    cout<<"Enter the word you want to insert into your new hashtable:"<<endl;
    cin<<str;

    //then inserts something into it
    insertIntoHash(OH, CH, HOH, str);
}

int main(){

    int type, size, limit;

    .
    //intructions that ask the user to enter the 3 values for type, size and limit
    .

    mainMenu(type, size, limit);

}

以上是我的程序结构的简化表示。我想拥有可以在三种类型的哈希表上运行的泛型函数。我相信我处理它的方式看起来非常业余,但这是因为它是一个非常古老的代码,我现在正在为一个大学项目添加新东西。我试图学习使用模板,虚函数,但它比我预期的要难(因为虽然每个类都有相同操作的函数(如插入,删除等),但它们有不同的构造函数,有些函数接收不同的参数,我现在没有时间从头开始重写所有内容。

1 个答案:

答案 0 :(得分:0)

从C ++ 17开始,你可以使用std::variant来保存3种不同实现中的一种,即使它们不共享公共接口。

当然,如果他们这样做,只需使用多态,只需将指针声明为基类型。

您发现的部分解决方案仍然存在问题,但是泄漏了。您将需要编写一个匹配的析构函数,再次删除实例化的对象,或者更简单:只使用智能而不是原始指针,从C ++ 11开始就可以使用它们。

具体而言,std::unique_pointer适用于此用例。为了分配它而通过引用传递指针的模式仍然适用于智能指针,除了你不必担心指针已经拥有对象。

相关问题