c++ - 包含并运行其他文件中的函数
问题描述
我有 2 个文件,main.cpp 和 xyz.cpp,xyz.cppp 具有进行一些计算的功能(并且应该在最后输出),我想从 main.cpp 中的 switch 调用这个函数
主.cpp:
#include <iostream>
#include <math.h>
#include <cstdlib>
#include "xyz.cpp"
int cl;
using namespace std;
int main(int argc, const char * argv[]){
cout << ("Make ur choice (1-1)");
cin >> cl;
switch(cl){
case (1):{
// I suppose it should be called here somehow
}
}
return 0;
}
xyz.cpp:
using namespace std;
int function() {
cout << "Input number: ";
cin >> a;
o1p1 = (1+cos(4*a));
o1p2 = (1+cos(2*a));
o1 = ((sin(4*a))/o1p1)*((cos(2*a))/o1p2);
cout << "\nZ1 = ";
cout << o1;
cout << "\n ";
return 0;
}
解决方案
重命名您的方法,否则调用将是模棱两可的。
使用名为“xyz.h”的头文件,在其中声明您的方法。然后,在 main.cpp 文件中,包含该头文件(而不是其源文件)。源文件“xyz.cpp”也应该包含头文件。然后在 main.cpp 中,像这样调用方法:int returnedValue = myFunction();
完整示例:
xyz.h
#ifndef XYZ_H
#define XYZ_H
int myFunction();
#endif /* XYZ_H */
xyz.cpp
#include <iostream>
#include <cmath>
#include "xyz.h"
using namespace std;
int myFunction() {
float a, o1p1, o1p2, o1;
cout << "Input number: ";
cin >> a;
o1p1 = (1+cos(4*a));
o1p2 = (1+cos(2*a));
o1 = ((sin(4*a))/o1p1)*((cos(2*a))/o1p2);
cout << "\nZ1 = ";
cout << o1;
cout << "\n ";
return 0;
}
主文件
#include <iostream>
#include "xyz.h"
using namespace std;
int main(int argc, const char * argv[]) {
int cl;
cout << ("Make ur choice (1-1)");
cin >> cl;
switch(cl){
case (1):{
int returnedValue = myFunction();
cout << returnedValue << endl;
}
}
return 0;
}
输出:
Georgioss-MBP:Desktop gsamaras$ g++ main.cpp xyz.cpp -lm
Georgioss-MBP:Desktop gsamaras$ ./a.out
Make ur choice (1-1)1
Input number: 2
Z1 = -2.18504
0
推荐阅读
- c - 如何将字体设置为用户使用字体选择器选择的字体?
- php - 删除获取请求的 url .php 扩展名和参数?
- vue.js - Vue js如何使用props值到v-model
- nginx - 使用 nginx 反向代理丢失 POST 请求正文
- arrays - 如何将 json 数据显示到 laravel 刀片中?
- php - php sqlsrv 通过多台服务器连接到一个特定的数据库
- java - 如何通过 LLRP 从 EPC RFID 标签读取用户数据(内存)?
- typescript - 如何修复 no-unsafe-any 规则?
- ios - 如何在 Swift 中使用查询语句检索数据?
- elasticsearch - ElasticSearch 词袋字段匹配