【问题标题】:(C++) My Function Does Not Return Array [duplicate](C++)我的函数不返回数组[重复]
【发布时间】:2019-02-01 05:32:50
【问题描述】:

我是 C++ 编程的新手。在下面的代码中,我希望用户输入员工人数和每个员工的销售额。然后程序会为每个员工写出相应的销售额。虽然编译器没有报错,但还是不行。你能帮我找出错误在哪里吗?提前致谢。

#include <iostream>
using namespace std;

int enterSales(int max){
    int sales[max];
    for (int idx=0;idx<max;idx++){
        cout<<"Enter the amount of sales for person #"<<idx<<": ";
        cin>>sales[idx];
    }
    return sales[max];
}

float showSalesComm(int max){
    int sales[]={enterSales(max)};
    for (int idx=0;idx<max;idx++){
        cout<<"The amount of sales for person #"<<idx<<": ";
        cout<<sales[idx]<<endl;
    }
    return 0;
}

int main () {

    int max;
    cout<<"Enter the number of employees.";
    cin>>max;
    showSalesComm(max); 

    return 0;
}

【问题讨论】:

  • int sales[max]; - 可变长度数组不是标准的 C++ 特性(尽管有些编译器很遗憾地接受它们作为扩展)。你想使用std::vector。此外,您的函数只返回 int - 您怎么会期望能够在那里返回一个数组(或 std::vector)?
  • 启用编译器警告。禁用编译器扩展。编译器会指出错误。
  • 如果您希望代码按照您认为应该的方式运行,并且不会因为指针问题而出现意外,请使用 std::vector&lt;int&gt; sales(max):。另外,返回std::vector&lt;int&gt;,而不仅仅是int。此外,int sales[]={enterSales(max)}; 则变为 std::vector&lt;int&gt; sales = enterSales(max);

标签: c++ arrays function


【解决方案1】:

您可以使用std::vector&lt;int&gt; 代替数组。在 C/C++ 中,数组在传入函数时分解为指针。让事情变得困难。

使用std::vector&lt;int&gt; 将负责分配和删除,最重要的是,您可以从函数中返回它们(复制构造),并且不会出现临时问题或其他问题。

这里是怎么做的。

#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::cin;
using std::endl;

vector<int> enterSales(int max){
    int temp;
    vector<int> a;
    for (int idx=0;idx<max;idx++){
        cout<<"Enter the amount of sales for person #"<<idx<<": ";
        cin>>temp;
        a.push_back(temp);
    }
    return a;
}

void showSalesComm(int max){
    vector<int> sales=enterSales(max);
    for (int idx=0;idx<max;idx++){
        cout<<"The amount of sales for person #"<<idx<<": ";
        cout<<sales[idx]<<endl;
    }
}

int main () {

    int max;
    cout<<"Enter the number of employees.";
    cin>>max;
    showSalesComm(max); 
    return 0;
}

实际上,您的代码中有很多错误。返回临时和索引超出界限等。禁用编译器扩展,它会显示警告。

【讨论】:

  • 所以需要使用动态内存分配 -- 改用std::vector&lt;int&gt;
  • 是的,我会将其添加到替代解决方案中,谢谢。
猜你喜欢
  • 2012-02-03
  • 1970-01-01
  • 2018-05-09
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
相关资源
最近更新 更多