多次创建相同的对象名称是否好用c ++

时间:2019-03-28 05:08:53

标签: c++

我有4栋楼,每栋楼都有10套公寓。 我为每个单元创建了一个类。班级单元

要创建一个对象,我需要参数单位myunit(int building,int apartments)

在程序开始时,我需要为每个单元创建一个对象并将其添加到vector中,这样做更好。

第一种方法,我得到的错误操作数类型为:unit = unit *

static fetchCurrentServices(){      
   return   fetch("http://localhost:8080/portal-backend/services",   {
        mode: "no-cors",
        method: "GET" ,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "application/json"
        } 
  })
  .then(
    res => res.json() 
  ).catch(function (ex) {
   console.log('parsing failed', ex)
    });
  }

第二种方式:创建相同的对象名称但参数不同

int main()
{
    int building[4] = {1,2,3,4 };
    int apts[10]  = {1,2,3,4,5,6,7,8,9,10 };
    vector<unit > units(40);
    int vectorCounter = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
            // I got error in the line below.operand type are:unit = unit*
            units[vectorCounter++] = new unit (building[i], apts [j]);  
        }
    }

第三种方式:与第二种方式相同,只是添加析构函数

int main()
{
    int building = {1,2,3,4 };
    int apts  = {1,2,3,4,5,6,7,8,9,10 };
    vector<unit > units(40);
    int vectorCounter = 0;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
        unit myunit(building[i], apts [j])   ;
            units[vectorCounter++] = myunit ;
        }
    }

哪种方法更好,为什么我第一种方法出错

1 个答案:

答案 0 :(得分:0)

首先,您在编写int building = {1,2,3,4 };

时并没有真正创建数组

应为int building[] = {1,2,3,4 };

编译错误是由于向量保持在单位对象上,但是您正在尝试为其分配指针。在第一种方法中,您可能想让向量存储unit *

您的第二种方法没问题,但是第三种方法是错误的,不会以这种方式调用析构函数,并且您不应该手动调用析构函数,编译器会在离开您的for循环范围时为您完成此操作。

我认为,最佳确实取决于您要使用矢量的方式,最快和最安全的方法将是第二种方法,它使用堆栈分配,并且速度极快且安全(无需手动调用删除)。由于所有内容在内存中都是顺序的,因此遍历所有单元的速度也很快。

Why should C++ programmers minimize the use of new