函数返回值不变

时间:2019-03-21 00:34:30

标签: c++

调用函数amount_of_people之后,变量n保持不变。我通过在函数调用后输出变量来验证这一点。我需要一个指针n来充当参数吗?

int main(){
srand(time(NULL));
bool Appworks = true;
size_t n;
    do {
        amount_of_people(n); // Entering amount of people HERE! STUCKED HERE.
        if (n >= 1) {
            DataBase *first = new DataBase[n]; // Creating dynamic structure-array
            inputData(first, n);

            output(first, n); // Output of entered data

            freeUp_memory(first); // Clearing dynamic-alocated memory engaged by early-created pointer


        }
        else cout << "Error! Wrong amount of people!" << endl;

    } while (Appworks);
system("PAUSE");
return 0;
}

函数声明:

unsigned amount_of_people(int n) {
    cout << "Enter how many people u want to enter" << endl;
    cin >> n;
    return n;
}

我将不胜感激() 感谢您的关注。

2 个答案:

答案 0 :(得分:2)

amount_of_people(n)

不使用从amount_of_people返回的值。 n在这里没有用,因为根据函数声明

unsigned amount_of_people(int n);

n按值传递。当参数通过值传递时,该函数对源变量的副本进行操作。更改副本对原件没有影响。我可以建议代替

std::size_t amount_of_people() // parameter gone, return type changed to match n in caller
{
    std::size_t n; // parameter moved to here and type changed to match return type
    std::cout << "Enter how many people u want to enter" << std::endl;
    std::cin >> n;
    return n;
}

然后像这样使用

const std::size_t n = amount_of_people();

旁注:而不是

DataBase *first = new DataBase[n];

强烈考虑确保DataBase正确遵守the Rule of Three, Five, or Zero并使用

std::vector<DataBase> databases;

而不是原始分配。它知道它的大小,并为您管理所有内存管理。 Documentation for std::vector

答案 1 :(得分:1)

RE“我需要一个指针来充当参数”,可以是指针,也可以是引用。

unsigned amount_of_people(int n)在您编写时按值取一个整数n,使用cin >> n进行分配,然后返回它。将功能更改为

void amount_of_people(unsigned int& n) {
    std::cout << "Enter how many people u want to enter" << endl;
    std::cin >> n;
}

并调用它:

amount_of_people(n);

通过引用获取n,或写

unsigned int amount_of_people() {
    unsigned int n;
    std::cout << "Enter how many people u want to enter" << endl;
    std::cin >> n;
    return n;
}

并调用它:

n = amount_of_people();

两种样式都有用途;我认为,第一种情况是在函数具有副作用的情况下更常见,因此它会将其结果“输出”到ref传递的参数(“ out参数”)中,而您选择从函数中返回一个指示执行期间是否发生错误。第二种样式在纯函数中更为常见,在这种情况下,总是根据输入成功地计算结果,而不会出错。

另外,请决定是否要将变量设为size_tint