简体   繁体   English

C ++中的指针; 细分错误错误:

[英]Pointers in C++; segmentation fault error:

I have just started to study C++, and right now I am working with pointers. 我刚刚开始学习C ++,现在我正在使用指针。 I cannot understand why the following thing is happening. 我不明白为什么发生以下情况。

So, say I have two classes A and B. A has an integer field (int valueA) and B has a pointer field (to A), A *a. 因此,假设我有两个类A和B。A具有一个整数字段(int valueA),而B具有一个指针字段(指向A),即A * a。 Below I have shown both classes. 下面我展示了两个类。

class A{
   A::A(int value){
    valueA = value;
}


 void A::displayInfo (){
      cout<<A<<endl;
    }
 }



class B{

    B::B(){
    a=0;
  }


  void B::printInfo (){
       a -> displayInfo(); //Segmentation fault
     }

  void B::process(){
     A new_A = A(5);
     a = &new_A;
     new_A.displayInfo(); //correct output
     a -> displayInfo();  //correct output
     }
  }

Now when in my main class I do the following: create an instance of the B class and call the process() and print() functions. 现在在我的主类中时,请执行以下操作:创建B类的实例,然后调用process()和print()函数。 In the output I get: 5(which is correct), 5(which is correct) and Segmentation fault. 在输出中,我得到:5(正确),5(正确)和分段错误。 Can anyone please help me understand why this is happening? 谁能帮我了解为什么会这样吗? According to my current understanding of pointers, I am doing the correct thing? 根据我对指针的当前理解,我正在做正确的事情?

int main(void) { int main(void){

B b_object();
b_object.process();
b_object.print();

} }


Just to make this clear, I have an Ah and Bh file where I declare "int valueA;" 为了清楚起见,我有一个Ah和Bh文件,其中声明“ int valueA;”。 and "A *a;" 和“ A * a;” respectively. 分别。 And I know this can be done much easier without pointers, but I am trying to learn how pointers work here :D 而且我知道没有指针也可以轻松完成这项工作,但是我正在尝试学习指针在这里的工作方式:D

 A new_A = A(5);
 a = &new_A;

Here you create new_A which is local to process and assign its address to a . 在这里,您创建new_A这是局部的process ,并将其地址分配给a When the process function ends, new_A goes out of scope and is destroyed. process函数结束时, new_A超出范围并被销毁。 Now a points at an invalid object. 现在a指向无效对象。

The real solution here is to not use pointers like this, but if you really have to, to have something last beyond the end of the function you need to dynamically allocate it. 真正的解决方案是不使用这样的指针,但如果确实需要,则在函数末尾保留一些内容,您需要动态分配它。 Do this with a = new A(5); a = new A(5); . You need to make sure that you delete a; 您需要确保delete a; at some later point in the program, otherwise the dynamically allocated memory will be leaked. 在程序的稍后位置,否则动态分配的内存将被泄漏。

a被分配给process()中的局部变量,因此在printInfo()中无效

变量a在您的方法中是本地的-在类级别声明它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM