从其他函数C++中获取函数中的变量

Obtain variables in function from other function C++

本文关键字:函数 变量 获取 C++ 其他      更新时间:2023-10-16

我正试图将一个变量从一个函数传递到另一个函数。我尝试过这种方法,但对我不起作用:

int c (){
    int x1,x2,y2,y1;
    system("cls"); 
    cout<<"Insert Value"<<endl
    cin>>x1;
    return x1;
}
int cd()
{
     int a;
     a=c();
     cout<<"X1: "<<a;
}

感谢您的帮助。谢谢

您的代码有一些问题。

首先,在c()函数的cout语句后面缺少一个分号。

此外,您已经指示函数cd()应该返回int,但您没有返回任何内容。

最后,除非显式调用这些函数,否则这些函数将不会开始执行。

试试这个:

#include <iostream>
using namespace std;
int c (){
    int x1,x2,y2,y1;
    cout<<"Insert Value"<<endl;
    cin>>x1;
    return x1;
}
int cd(){
     int a;
     a=c();
     cout<<"X1: "<<a;
     return a;
}
int main()
{
    int x=cd(); //call the function to create the side effects
    return 0;
}