C++ 不允许像您尝试的那样多次重新运行。有多种方法可以做到这一点。
解决方案一:传递指向值的指针并在read函数中设置它们:
#include <iostream>
using namespace std;
void read(int* n1, int* n2, int* n3);
void display(int n1, int n2, int n3);
int main()
{
int n1, n2, n3;
read(&n1, &n2, &n3);
display(n1, n2, n3);
//print(n1,n2,n3);
//reverse(n1,n2,n3);
return 0;
}
void read(int* n1, int* n2, int* n3)
{
cout << "Enter three numbers: ";
cin >> *n1;
cin >> *n2;
cin >> *n3;
}
void display(int n1, int n2, int n3)
{
cout << n1 << " " << n2 << " " << n3 << endl;
return;
}
另外,对于同样的方法,您可以处理引用而不是指针,在 C++ 中,通过引用传递可以应用于所有类型,而不仅仅是原始类型。它看起来像这样:
void read(int &n1, int &n2, int &n3)
{
cout << "Enter three numbers: ";
cin >> n1;
cin >> n2;
cin >> n3;
}
调用它的函数main 会变成:
read(n1, n2, n3);
请注意,& 存在于 read 函数签名中至关重要,以确保您通过引用而不是值传递。按值传递不会反映原来传递的参数。
这与通过指针传递的效果相同,但看起来更简洁,并且不需要您使用*。
解决方案二:在 cpp 文件中声明它们是全局的。我不推荐这种解决方案,因为函数最好携带自己的数据,而不是过多地依赖全局变量,除非没有其他方法。一般来说,类/结构更适合这个。
#include<iostream>
void read(void);
void display();
int n1, n2, n3; // declared here
using namespace std;
int main()
{
read();
display();
//print(n1,n2,n3);
//reverse(n1,n2,n3);
return 0;
}
void read(void)
{
cout << "Enter three numbers: ";
cin >> n1;
cin >> n2;
cin >> n3;
}
void display()
{
cout << n1 << " " << n2 << " " << n3 << endl;
return;
}
解决方案三:使用数据结构来保存值并进行处理。在这种方法中,我们将 n1 n2 n3 作为结构的一部分,并从函数中获取它。
#include<iostream>
struct data{
int n1;
int n2;
int n3;
}
data read(void);
void display(data);
using namespace std;
int main()
{
data d = read();
display(d);
//print(n1,n2,n3);
//reverse(n1,n2,n3);
return 0;
}
data read(void)
{
data d;
cout << "Enter three numbers: ";
cin >> d.n1;
cin >> d.n2;
cin >> d.n3;
return d;
}
void display(data d)
{
cout << d.n1 << " " << d.n2 << " " << d.n3 << endl;
return;
}
正如其他人在 cmets 中建议的那样,您也可以使用 std::tuple 返回多个值,它的工作方式类似于在解决方案三中使用 data struct 的方式,这是我最推荐给您的解决方案案例:
#include <iostream>
#include <tuple>
using namespace std;
tuple<int, int, int> read(void);
void display(tuple<int, int, int>);
int main()
{
tuple<int, int, int> d = read();
display(d);
//print(n1,n2,n3);
//reverse(n1,n2,n3);
return 0;
}
tuple<int, int, int> read(void)
{
int n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1;
cin >> n2;
cin >> n3;
return std::make_tuple(n1, n2, n3);
}
void display(tuple<int, int, int> d)
{
cout << std::get<0>(d) << " " << std::get<1>(d) << " " << std::get<2>(d) << endl;
return;
}