简体   繁体   中英

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. 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. Can someone please explain why? I am a little rusty with C++ and feel like I am making a silly mistake. 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. For example, the function definition for start in Timer.cpp needs to be

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

All of the other functions in the Timer.cpp file need to follow that same syntax. In addition the startTime and stopTime variables should go in the Timer.h file like this:

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:

 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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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