我尝试在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”时,我就会要求OS给我一定数量的字节,以便在堆中存储类的新实例。
有什么方法可以把我的类存储在堆栈中吗?
在堆栈上创建您的对象(即类实例)的方式甚至更简单--局部变量存储在堆栈上。
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++中使用new关键字?