我尝试在 C++ 中玩一点内存,我为自己定义了一个类,然后在堆中创建了该类的一个实例。
#include <iostream>
class mojeTrida {
public:
void TestPrint()
{
std::cout << "Ahoj 2\n";
}
};
int main() {
mojeTrida *testInstance = new mojeTrida();
testInstance->TestPrint();
std::cout << "Hello World!\n";
}
如果我对 C++ 的理解正确,每当我调用关键字“new”时,我就是在要求操作系统给我一定数量的字节来在堆中存储类的新实例。
有什么方法可以将我的类存储在堆栈中?
最佳答案
在堆栈上创建对象(即类实例)的方法更简单——局部变量存储在堆栈上。
int main() {
mojeTrida testInstance; // local variable is stored on the stack
testInstance.TestPrint();
std::cout << "Hello World!\n";
}
根据您的评论,您已经注意到,在调用对象的方法时,使用运算符 .
而不是 ->
。 ->
仅与指向取消引用它们的指针一起使用,并同时访问它们的成员。
带有指向局部变量的指针的示例:
int main() {
mojeTrida localInstance; // object allocated on the stack
mojeTrida *testInstance = &localInstance; // pointer to localInstance allocated on the stack
testInstance->TestPrint();
std::cout << "Hello World!\n";
// localInstance & testInstance freed automatically when leaving the block
}
另一方面,您应该删除
使用new
在堆上创建的对象:
int main() {
mojeTrida *testInstance = new mojeTrida(); // the object allocated on the heap, pointer allocated on the stack
testInstance->TestPrint();
delete testInstance; // the heap object can be freed here, not used anymore
std::cout << "Hello World!\n";
}
关于c++ - 在堆栈上创建类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556091/