c++ 如何在堆内存上创建类的示例

f1tvaqid  于 2022-12-24  发布在  其他
关注(0)|答案(5)|浏览(130)

已经为你定义了一个名为“Pair”的类类型。你需要写一个名为pairFactory的函数,在堆上创建一个Pair的示例。不要在堆栈上创建对象。然后,你的函数需要返回一个指针,指向那个创建的对象。
我已经写了pairFactory的代码。它看起来可以运行,但是我得到了一个infraError。请帮助我找到我的错误。另外,我需要在堆内存中创建对象。

#include <iostream>

// This class Pair has already been defined for you.
// (You may not change this definition.)
class Pair {
public:
  int first, second;
  void check() {
    first = 5;
    std::cout << "Congratulations! The check() method of the Pair class \n has executed. (But, this isn't enough to guarantee \n that your code is correct.)" << std::endl;
  }
};

Pair *pairFactory() {
  //
    Pair P;
    P.check();
  // (You can use as many lines as you want.)
  return &P;
}

// Your function should be able to satisfy the tests below. You should try
// some other things to convince yourself. If you have a bug in this problem,
// the usual symptom is that after you submit, the grader will crash with a
// system error. :-)
int main() {
    Pair *p;
    p = new pairFactory();

  // This function call should work without crashing:
  p->check();

  // Deallocating the heap memory. (Assuming it was made on the heap!)
  delete p;

  std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;

  return 0;
}
4xrmg8kj

4xrmg8kj1#

你把它弄反了,你的工厂需要在堆上分配,你所做的是返回一个不再存在的函数局部对象的地址。

Pair *pairFactory() {
  return new Pair;
}

然后在主函数中:

Pair *p = pairFactory();
jjjwad0x

jjjwad0x2#

在此返回对局部变量的引用。

Pair *pairFactory() {
    Pair P;
    P.check();
  return &P; // Dangling pointer
}

所以你有一个悬空指针,一旦你离开这个函数。
你得打电话给new

Pair *pairFactory()
{
  return new Pair{};
}

main可能类似于:

int main() {
  Pair* p = pairFactory();

  // This function call should work without crashing:
  p->check();

  // Deallocating the heap memory. (Assuming it was made on the heap!)
  delete p;

  std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}

最好使用智能指针,而不必自己管理内存:

std::unique_ptr<Pair> pairFactory()
{
    return std::make_unique<Pair>();
}

int main() {
    auto p = pairFactory();

    p->check();
    std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}
5w9g7ksd

5w9g7ksd3#

你做了你被告知 * 不 * 做的事:

Pair *pairFactory() {
    Pair P; // <----- creates an instance of Pair on the stack
    …
}

本练习的目的可能是测试您对new运算符的了解。

xdyibdwo

xdyibdwo4#

该功能

Pair *pairFactory() {
    return &P;
}

返回一个指向本地堆栈内存的指针,该指针在返回main()时立即被销毁/无效。

pb3s4cty

pb3s4cty5#

你的代码的问题是它返回了一个指针,但没有指向任何东西,因为P只存在于返回p的值之前,存储在堆内存中。使用new关键字将分配堆内存,并返回一个指向该值的指针。

Pair *pairFactory() {
 Pair P;
 P.check();
return &P;
}

相关问题