【问题标题】:Are there only two ways to create new objects in C++? (using and without using the `new` keyword)在 C++ 中创建新对象只有两种方法吗? (使用和不使用 `new` 关键字)
【发布时间】:2019-06-12 00:41:47
【问题描述】:

除非我记错了,

Rectangle rect(3,4); 使用 3 和 4 作为参数调用 Rectangle 的构造函数,但不会将创建的对象分配给指针或引用或变量或任何东西。

Rectangle* rect = new Rectangle(3,4); 创建一个对象和一个指向该对象的指针(new 总是返回一个指针,这就是为什么类型是指向矩形的指针而不仅仅是矩形。我认为。)

除了这两种方式,还有什么方法可以创建和对象吗?我对对象初始化有什么误解吗?

编辑:抱歉,错字,rect 是一个变量,但它不是指针或引用。

【问题讨论】:

  • 您真的应该花 几周(甚至 几个月)来阅读更多关于 C++ 的信息;这是一门的语言。阅读this book;你的问题实在是太宽泛了,而且 StackOverflow 不是一个“教我 C++”的论坛
  • 了解堆栈与堆的不同之处。
  • "不将创建的对象分配给指针或引用或 变量 或任何东西。" 如果不是变量,rect 是什么?
  • C++ move 语义是一个困难的概念,即使对我(编写了数十万行 C++ 代码)来说也是如此
  • 还有其他非常晦涩的创建对象的方法。但不清楚您所说的“我对对​​象初始化有什么误解吗?”你认为你误解了什么?

标签: c++ oop


【解决方案1】:

不,有更多方法可以在 C++ 中创建新对象。

来自 C++ 17 标准 (intro.object/1):

在隐式更改联合的活动成员或创建临时对象时,通过定义、new 表达式创建对象。

例子:

struct Rectangle {
    Rectangle(int x, int y);
    int x, y;
};

Rectangle rect(3,4); // object created by definition. Object has static storage duration

void fun() {
    Rectangle rect(3,4); // object created by definition. Object has automatic storage duration


    new Rectangle(3,4); // object created by new expression Object has dynamic storage duration. Note, it is possible to create object without assigning it to any pointer or reference
}

int temp() {
    return Rectangle(1, 2).x; // temporary object created with automatic storage duration
                              // this is just an example and it is not the only way to create temporary object
}

// Following code can be skipped if you don't know about unions yet
struct A {
    int x;
};

union B {
 A a;
 int z;
};

void test() {
    B b;
    b.a.x = 5; // Creates b.a object.
}

【讨论】:

    【解决方案2】:

    创建对象有4种方式,列在[intro.object]/1

    通过定义新表达式、隐式更改联合的活动成员或当创建了一个临时对象。 [...]

    加粗我的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多