0

Possible Duplicate:
Regarding C++ Include another class

i am new and would like to learn more about how do i split my C++ file into .h and .cpp

this is my File2.cpp

#include <iostream>
#include <string>

using namespace std;

class ClassTwo
{
private:
string myType;
public:
void setType(string);
string getType();
};


void ClassTwo::setType(string sType)
{
myType = sType;
}

void ClassTwo::getType(float fVal)
{
return myType;
}

I want split it into 2 files, which is .h and .cpp how do i split this as its a class, with private & public.

And I would like to use ClassTwo in File1.cpp(another cpp file)

How do i link it so i can use it at ClassTwo

Thanks for help.

Community
  • 1
  • 1
baoky chen
  • 799
  • 2
  • 11
  • 20

2 Answers2

4

//File2.h

#include <iostream>
#include <string>


class ClassTwo
{
private:
   std::string myType;
public:
   void setType(std::string);
   std::string getType();
}; 

//File2.cpp

#include"File2.h"

void ClassTwo::setType(std::string sType)
{
    myType = sType;
}

std::string ClassTwo::getType()
{
    return myType;
} 

//File1.cpp

#include "File1.h"   //If one exists
#include "File2.h"


int main()
{
    ClassTwo obj;
    return 0;
}

On a side note, I already explained this in very much detail on your previous question here.
Did you even read it?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • How do i use ClassTwo at File1.cpp , do i Include "File2.h" or "File1.h" at File1.cpp – baoky chen Oct 05 '12 at 05:11
  • @baokychen: I already gave you an complete example in answer above. Why do you think it does not answer the Q you asked? Have you read my answer to your previous Q? If you did, You wouldn't be asking the Q. – Alok Save Oct 05 '12 at 05:13
  • @Als - your example has a typo -- line 1 of File1.cpp should read `#include "File2.h"`. – Robᵩ Oct 05 '12 at 05:15
  • @Robᵩ: Oops just noticed.Fixed While you were adding the comment.Actually, I spent a lot of effort answering OPs previous Q(see link inline to answer) with lot of detail and I am surprised OP comes back again and asks the same thing. – Alok Save Oct 05 '12 at 05:16
  • @Als, thanks for answering. all is sorted now. – baoky chen Oct 05 '12 at 05:20
1

We can go on about the varying facets involved in separating the files into .cpp and .h/.hpp, however, I think this link will be of great use to you:

http://www.learncpp.com/cpp-tutorial/89-class-code-and-header-files/

Additionally, you will also want to avoid "using namespace std;" as the compiler unnecessarily loads the entire C++ standard namespace. In addition to that, doing so can inadvertently cause function name collisions, etc. In practice, load only the things from the standard namespace that you will use, or will use frequently.

See here for more:

Why is "using namespace std" considered bad practice?

Community
  • 1
  • 1
jrd1
  • 10,358
  • 4
  • 34
  • 51