需要“一”对象,如何使用“新” [英] Need "one" object, how to use "new"

查看:119
本文介绍了需要“一”对象,如何使用“新”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了;

Element element=new Element;

我遇到了错误;

homework.cpp: In function 'int main(int, char**)':
homework.cpp:227:29: error: conversion from 'Element*' to non-scalar type 'Element' requested

*** 1 errors, 0 warnings

I不想要一个指针或数组数组,

I do not want a pointer or array of elements,

Altough应该写 Element * element = new Element;
SOmebody要解释?

Altough should i write Element *element= new Element;. SOmebody to explain?

编辑:

元素类:

class Element{
  public:
      Element():exists(false){};

      std::string name;
      std::string full_path_name;
      ElementType element_type;
      long element_size;
      bool exists;

  };


推荐答案

如果你想分配一个动态对象,

If you want to allocate a dynamic object, it would be

Element* element = new Element;

因为 new 在免费商店。当您完成使用对象以防止内存泄漏后,您必须调用 delete元素。如果您不想手动管理内存,可以使用 std :: unique_ptr

Because new returns a pointer to the object in the free store. You have to call delete element when you're done using the object to prevent memory leaks. If you want to avoid having to manually manage the memory, you can use std::unique_ptr:

std::unique_ptr<Element> element = new Element;

并且元素会调用 delete 在指针超出范围时自动。但是,您确定不想只创建一个自动对象吗?

And element will call delete on the pointer automatically when it goes out of scope. However, are you sure you don't want to just create an automatic object?

Element element;

这会在自动存储中创建对象,而不必手动取消分配 使用智能指针,而且速度更快;它是最好的方式。 (但是确保你不要做 Element element(); 这是一个函数的原型,而不是一个变量声明。)

This creates the object in automatic storage and you don't have to manually deallocate it or use smart pointers, and it's a lot faster; it's the best way. (But make sure you don't do Element element(); which is the prototype for a function, not a variable declaration.)

这篇关于需要“一”对象,如何使用“新”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆