-2

I'm having difficulties placing a class into a separate file and calling it in the main. Below is my simple code.

Wondering how i can use the getKey() function into the int main()

#include "stdafx.h"
#include <iostream>
#include <string>
#include "TravelFunctions.h"


using namespace std;

TravelFunctions::getKey()

{
    cout << "i am a bananna" << endl;
}

my TravelFunction.h class

class TravelFunctions

{
    public:
           getKey();

}

my main class

#include "stdafx.h"
#include <iostream>
#include <string>
#include "TravelFunctions.h"


using namespace std;

int main()
{
    getKey bo;
    return 0;

}
arserbin3
  • 6,010
  • 8
  • 36
  • 52
user2201189
  • 79
  • 1
  • 1
  • 8
  • Is this your actual code? Because even if these were all in the same file, you have syntax errors all over – Collin May 02 '13 at 12:51
  • 1
    First you have to learn how to declare a function. You are missing the return type. Next, how to declare a class. You are missing a trailing `;`. Then, how to call a function, and finally, how to call a member function. – juanchopanza May 02 '13 at 12:51
  • In your main code, you need to create in instance of TravelFunctions and then call the getKey() method on that. It looks like the methods inside the TravelFunctions should be static (in which case you would not need to instantiate a TravelFunctions object). Or alternatively you could define free standing functions in a namespace named TravelFunctions. – rohitsan May 02 '13 at 12:52
  • yes. i am having difficulties in separating my work into different classes. At the moment all my work is in int main(). i am trying to learn how to separate these. :S – user2201189 May 02 '13 at 12:53
  • im trying so i will be able to create more than 1 function in the travelfunction class so i will be able to call these inside the int main() – user2201189 May 02 '13 at 12:55

2 Answers2

3

You have to first instance an object from your class. Your main function should look like this:

int main()
{
    TravelFunctions functions;

    functions.getKey();

    return 0;
}

You should also define void as the return type of your function.

.cpp:

void TravelFunctions::getKey()
{
    cout << "i am a bananna" << endl;
}

.h:

class TravelFunctions
{
    public:
           void getKey();

}; // Notice that you have to add ; after the class definition
Scintillo
  • 1,634
  • 1
  • 15
  • 29
1
TravelFunctions obj;
obj.getKey();

You need a class instance to call a member function.

You should definitely get a good book.
The Definitive C++ Book Guide and List

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533