简体   繁体   English

如何从main.cpp文件中的单独cpp文件中调用函数?

[英]How to call a function from a separate cpp file in the main.cpp file?

I have the following Timer.cpp, Timer.h, and main.cpp files. 我有以下Timer.cpp,Timer.h和main.cpp文件。 I am trying to call functions from the Timer.cpp file in my main.cpp file and have included the Timer.h in the main, but it is still not working. 我正在尝试从main.cpp文件中的Timer.cpp文件调用函数,并且已将Timer.h包含在主函数中,但仍无法正常工作。 Can someone please explain why? 有人可以解释为什么吗? I am a little rusty with C++ and feel like I am making a silly mistake. 我对C ++有点生疏,觉得自己犯了一个愚蠢的错误。 Thanks in advance for any help. 在此先感谢您的帮助。

#Timer.h file

#ifndef __Notes__Timer__
#define __Notes__Timer__

#include <iostream>

class Timer {
public:
    Timer();
    void start();
    void stop();
    void clear();
    float getDelta();
};

#endif

#Timer.cpp file    
#include "Timer.h"


clock_t startTime;
clock_t stopTime;

Timer::Timer(){
    startTime = 0;
    stopTime = 0;
}//Timer

void start(){
    startTime = clock();
}//start

void stop(){
    stopTime = clock();
}//stop

float getDelta(){
    return stopTime-startTime;
}//getDelta

#main.cpp file

#include "Timer.h"
#include <iostream>

using namespace std;


int main(){
    char quit;
    start();
    cout << "Would you like to quit? Y or N: ";
    cin >> quit;
    if (quit != 'Y' || quit != 'y'){
        while (quit != 'Y' || quit != 'y'){
            cout << "Would you like to quit? Y or N: ";
            cin >> quit;
        }//while
    }//if
    else {
        stop();
        cout << getDelta();
        exit(0);
    }//else
}//main

您可以在Timer.c中使用这些功能,并使用此类class :: function

It seems the reason it is not working is because of two things: Your Timer function definitions are not tied to the Timer class. 似乎它不起作用的原因是由于两件事:您的Timer函数定义未绑定到Timer类。 For example, the function definition for start in Timer.cpp needs to be 例如,Timer.cpp中start的函数定义需要为

     void Timer::start()
     {
       //Do stuff
     }

All of the other functions in the Timer.cpp file need to follow that same syntax. Timer.cpp文件中的所有其他功能都需要遵循相同的语法。 In addition the startTime and stopTime variables should go in the Timer.h file like this: 另外,startTime和stopTime变量应放在Timer.h文件中,如下所示:

class Timer
{
  private:
    clock_t startTime;
    clock_t stopTime;

  public:
    Timer();
    void start();
    //etc
}

Next, in the main function, you need to create a Timer object: 接下来,在主函数中,您需要创建一个Timer对象:

 int main()
 {
   char quit;
   Timer* timer_obj = new Timer();
   timer_obj -> start();
   //Do stuff
   timer_obj -> stop();
   cout << timer_obj -> getDelta() ;
   delete timer_obj ;
   //exit
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM