两个函数变量合并到一个函数中
Two functions variables in to a single function
我在两个不同的函数中有两个变量,我想将它们存储在第三个函数中,而不使用全局变量。怎么做呢?
像这样的
void function1() {
a = 1;
b = 2;
}
void function2() {
c = 3;
d = 4;
}
void function3 () {
cout << a;
cout << b;
cout << c;
cout << d;
}
您的函数可以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;
}
演示工作使函数成为类的方法,变量成为类的属性。
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;
}
};
使用引用传递:
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;
}
您可以通过引用传递它们
#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);
}
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何仅为一个函数添加延迟
- 构造函数正在调用一个使用当前类类型的函数
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 如何创建函数管道,以便函数一个接一个地运行?
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 在c++中的复制构造函数/一个声明语句中的初始化的延续中使用chain方法
- C :基类调用自己的虚拟函数 - 一个反图案
- 如何在这个交换函数(一个单独的链表)中找到错误
- 两个相同的函数(一个使用模板模式,另一个不使用)
- 你怎么能一次给一个函数一个参数呢
- 为什么要做两个函数?(一个是非const,另一个是const)
- 当代码在其他地方使用时,如何保证函数一个接一个地被调用