【问题标题】:Unable to understand what type the function is returning [closed]无法理解函数返回的类型 [关闭]
【发布时间】:2021-03-30 08:24:47
【问题描述】:

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

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;
} 



    
   

```

【问题讨论】:

    标签: c++ sorting oop pointers stack


    【解决方案1】:

    这里有很多问题。指向堆栈的指针是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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多