C++ 如何在堆内存上创建类的实例
已经为您定义了一个名为“Pair”的类类型。您需要编写一个名为pairFactory的函数,在堆上创建Pair的实例。不要在堆栈上创建对象。然后,函数需要返回指向所创建对象的指针 我已经为pairFactory编写了代码。它似乎在运行,但我发现了一个错误。 请帮我找出我的错误。 另外,我需要在堆内存中创建对象C++ 如何在堆内存上创建类的实例,c++,class,instance,C++,Class,Instance,已经为您定义了一个名为“Pair”的类类型。您需要编写一个名为pairFactory的函数,在堆上创建Pair的实例。不要在堆栈上创建对象。然后,函数需要返回指向所创建对象的指针 我已经为pairFactory编写了代码。它似乎在运行,但我发现了一个错误。 请帮我找出我的错误。 另外,我需要在堆内存中创建对象 #include <iostream> // This class Pair has already been defined for you. // (You may no
#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;
}
#包括
//已经为您定义了此类对。
//(您不能更改此定义。)
类对{
公众:
int第一,第二;
无效检查(){
第一个=5;
std::cout你已经把它倒过来了。你的工厂需要在堆上分配。你正在做的是返回一个不再存在的函数本地对象的地址
Pair*pairFactory(){
返回新的一对;
}
然后在您的主要功能中:
Pair*p=pairFactory();
您可以在此处返回对局部变量的引用
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;
}
intmain(){
Pair*p=pairFactory();
//此函数调用应在不崩溃的情况下工作:
p->check();
//释放堆内存。(假设它是在堆上生成的!)
删除p;
std::cout你完全按照被告知的那样做:
Pair*pairFactory(){
对P;//函数
Pair *pairFactory() {
return &P;
}
返回指向本地堆栈上内存的指针,该内存在返回main()时即被销毁/无效。您必须使用运算符new创建对。
。分配此作业的人是否告诉您“堆上”是什么意思是?我得到一个错误-->错误:无法将assignmentOn堆内存中的“int*”转换为“Pair*”,而不是堆栈内存。
Pair *pairFactory() {
Pair P; // <----- creates an instance of Pair on the stack
…
}
Pair *pairFactory() {
return &P;
}