两个函数变量到单个函数中

时间:2015-08-07 17:50:22

标签: c++

我在两个不同的函数中有两个变量,我想将它们存储在第三个函数中,而不使用全局变量。 怎么做?

类似这样的事情

void function1() { 
  a = 1;
  b = 2;
}

void function2() {
  c = 3;
  d = 4;
}

void function3 () {
  cout << a;  
  cout << b;  
  cout << c;  
  cout << d;  
}

4 个答案:

答案 0 :(得分:6)

您的函数可以return值,因此您可以将变量传递给其他函数,例如

std::pair<int, int> function1() {
    int a = 1;
    int b = 2;
    return {a, b};
}

std::pair<int, int> function2() {
    int c = 3;
    int d = 4;
    return {c, d};
}

void function3 () {
    int a, b, c, d;
    std::tie(a, b) = function1();
    std::tie(c, d) = function2();
    std::cout << a;  
    std::cout << b;  
    std::cout << c;  
    std::cout << d;  
}

Working demo

答案 1 :(得分:4)

创建类的函数方法,以及类的变量属性。

class A
{
public:
int a;
int b;
int c;
int d;

void function1() { 
  a = 1;
  b = 2;
}

void function2() {
  c = 3;
  d = 4;
}

void function3 () {
  cout << a;  
  cout << b;  
  cout << c;  
  cout << d;  
}
};

答案 2 :(得分:4)

使用传递引用:

int main() {
    int a;
    int b;
    function1(a, b);

    int c;
    int d;
    function2(c, d);

    function3(a, b, c, d);

    return 0;
}

void function1(int& a, int& b) { 
  a = 1;
  b = 2;
}

void function2(int& c, int& d) {
  c = 3;
  d = 4;
}

void function3(int a, int b, int c, int d) {
  cout << a;  
  cout << b;  
  cout << c;  
  cout << d;  
}

答案 3 :(得分:2)

您可以通过引用传递它们

#include<iostream>
using namespace std;
void function1(int &a,int &b) {
    a = 1;
    b = 2;

}

void function2(int &c, int &d) {
    c = 3;
    d = 4;
}

void function3(int a1,int b1,int c1,int d1) {

    cout << a1;
    cout << b1;
    cout << c1;
    cout << d1;
}
int main(){
    int a = 0, b = 0, c = 0, d = 0;
    function1(a, b);
    function2(c, d);
    function3(a, b, c, d);



}