我正在尝试使用 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";
}
Run Code Online (Sandbox Code Playgroud)
如果我正确理解了 c++,每当我调用关键字“new”时,我都会要求操作系统给我一定数量的字节来在堆内存储类的新实例。
有什么办法可以将我的类存储在堆栈中吗?
Mel*_*ius 10
在堆栈上创建对象(即类实例)的方法更简单——局部变量存储在堆栈中。
int main() {
mojeTrida testInstance; // local variable is stored on the stack
testInstance.TestPrint();
std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)
正如您根据您的评论所注意到的.,->在调用对象的方法时使用运算符而不是。->仅与指针一起使用以取消引用它们并同时访问它们的成员。
带有指向局部变量的指针的示例:
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
}
Run Code Online (Sandbox Code Playgroud)
另一方面,您应该delete使用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";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |