首页 > 解决方案 > 包含并运行其他文件中的函数

问题描述

我有 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;

}

标签: c++function

解决方案


重命名您的方法,否则调用将是模棱两可的。

使用名为“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

推荐阅读