微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法理解函数返回的类型

如何解决无法理解函数返回的类型

我正在尝试使用另一个堆栈和临时变量对堆栈进行排序。在排序函数中,当我尝试返回第二个堆栈的地址时,我不确定它返回的是什么类型。因为我收到了两个错误

file0.cpp: In function 'int main()':  
file0.cpp:97:23: error: cannot convert 'int*' to 'stack*'
   97 |     arr.ad = sort(one.a);

file0.cpp:46:17: note:   initializing argument 1 of 'int sort(stack*)'
   46 | int sort(stack* obj){
      |          ~~~~~~~^~~

所以,这些是我得到的错误。通过将排序功能更改为:

,我尝试了很多事情
stack* sort();
 int* sort();

它们都运行良好。那么任何人都可以解释代码有什么问题并纠正它吗?我必须更好地学习哪些主题才能不再犯这样的错误

#include <iostream>
#define MAX 101
using namespace std;

class stack{

public:
int top = -1,a[MAX];
int address;

void push(int x){
   
   a[++top] = x;
}

void pop(){
   top = top - 1;
}

bool isEmpty(){
   if(top == -1){
       return true;
   }else{
       return false;
   }
}

int Top(){
   return top;
}



void print(stack* arr){    //a function to print the stack just confirmaion
   for(int i = 0; i < top; i++){ //that the stack is sorted
      cout << arr->a[i];
   }
 }


 };




 int sort(stack* obj){  //function to sort the stack



 int n = obj->top;
 int temp = obj->a[n]; //a variable to hold the element
 //if it is greater than the Top stack during sorting

 stack two; //second stack for sorting the elements
 if(two.isEmpty()){    //
    two.push(temp);
 }

  
 while(obj->top != 0){
  
  if((temp > obj->a[obj->top]) & (two.a[two.top] > temp)){
      two.push(temp);
  }else if(two.a[two.top] > obj->a[obj->top]){
      two.push(obj->a[obj->top]);
      obj->pop();
  }else{
      temp = obj->a[obj->top];
      obj->pop();
      obj->push(two.a[two.top]);
      two.pop();
  }

 }


  return two.a; //trying to return
  //address of the second stack that I created

 
  }

int main() {
stack one;
one.push(12); //pushing into the stack
one.push(1);
one.push(19);
one.push(14);
one.push(7);
one.push(79);
one.push(3);

stack* a;
a->address = sort(one.a);
one.print(a->address);
return 0;
} 



    
   

```

解决方法

这里有很多问题。指向堆栈的指针是 stack*,但 two.a 不是指向堆栈的指针,而是指向该堆栈内的 a 数组的指针,即 int*

但是整个方法是错误的。 stack twosort 函数内的局部变量。因此,当您退出 sort 函数时,它会被销毁。所以如果你要返回一个指向它的指针,或者一个指向它内部数组的指针,你将返回一个指向不再存在的东西的指针,你的程序会崩溃。

处理这个问题的简单方法是返回堆栈本身,而不是一个指针。我还更改了 sortprint,以便它们使用引用而不是指针。

似乎(像许多初学者一样)您使用指针来解决通过其他方式更好地解决的问题的速度太快了。指针绝对是 C++ 的高级特性,但在高质量的 C++ 代码中很少需要。

像这样

stack sort(stack& obj)
{
    int n = obj.top;
    ...
    stack two;
    ...
    return two;
}

void print(const stack& arr){
    ...
}

int main()
{
    stack one;
    one.push(12);
    ...
    stack a = sort(one);
    print(a);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。