箭头“->”从类调用函数时,分隔符崩溃 [英] the arrow '->' separator is crashing when calling function from class
问题描述
我正在为一个类工作,我正在使用类和类型类的指针来调用类中的某些函数,但是在代码块和Eclipse上崩溃了,我不知道$ b发生了什么$ b请注意,将x分配给y时会崩溃
I'm working on a project for class and I'm using classes and pointers of type class to call some functions in the class but it's crashing on Code Blocks and Eclipse and I don't know what is going on Note it crashes when assigning x with y
#include <iostream>
using namespace std;
class a{
private:
int x;
public:
void set_X(int y){
x=y;
}
};
int main()
{
a *Ptr;
Ptr->set_X(5);
}
推荐答案
a *Ptr;
Ptr->set_X(5);
您的 Ptr
没有指向任何东西。尝试在未初始化的指针上调用成员函数会导致未定义的行为。崩溃只是可能发生的或多或少的随机事件之一。
Your Ptr
does not point to anything. Trying to invoke a member function on an uninitialised pointer results in undefined behaviour. Crashing is just one of the many more or less random things that can happen.
幸运的是,在您的示例中,无论如何您都不需要指针。您可以简单地写:
Luckily, in your example, you do not need a pointer anyway. You can simply write:
a my_a;
my_a.set_X(5);
指针通常指向动态分配的对象。如果这是您想要的,则必须使用 new
并相应地删除
:
Pointers often point to dynamically allocated objects. If this is what you want, you must use new
and delete
accordingly:
a *Ptr = new a;
Ptr->set_X(5);
delete Ptr;
在现代C ++中, std :: unique_ptr
通常是一种更好的选择,因为您不必手动释放分配的内存,从而消除了许多潜在的编程错误:
In modern C++, std::unique_ptr
is typically a superior alternative because you don't have to manually release the allocated memory, which removes a lot of potential programming errors:
auto Ptr = std::make_unique<a>();
Ptr->set_X(5);
// no delete necessary
这篇关于箭头“->”从类调用函数时,分隔符崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!