im creating class so i can underst开发者_Go百科and them better. when im creating a class what should header files be used for and cpp?
Header files is for the class definition and the cpp file for the implementation. Something like this:
Test.h
class Test
{
public:
void PrintHelloWorld(void);
};
Test.cpp
void Test::PrintHelloWorld(void)
{
cout << "Hej på dig världen!";
}
This is a really basic question. You should probably find a C++ tutorial or book to help you out.
A header file has the class definition.
A cpp file has the class implementation.
Header file should include "#include" directives, constants definition and definition of class methods: constructors, destructors and methods. Think about it like you define an interface of the class.
Cpp should contain the implementation. So in cpp you realise all that you declared in .h file.
Here is an example:
CBug.h:
#ifndef CBUG_H
#define CBUG_H
#include <string>
#include <vector>
using namespace std;
enum BugState
{
ILLEGAL = -1,
ACTIVE = 0,
RESOLVED,
CLOSED
};
/**
* CBug - class to describe the record about any bug
*/
class CBug
{
private:
string DevName;
string Project;
int Id;
string ErrorDesc;
BugState State;
// class constructor
CBug();
public:
// class destructor
~CBug();
/**
* CreateBug
* creates a new bug, reads values from string and returns a pointer to a bug
* @param Params contains all necessary information about bug
* @return pointer to a newly created bug
*/
static CBug * CreateBug ( string Params );
// setters
void SetState( BugState );
//getters
string GetDeveloper( );
int GetId();
int GetState( );
bool IsActive( );
string ToString( );
};
#endif // CBUG_H
CBug.cpp:
// Class automatically generated by Dev-C++ New Class wizard
#include "CBug.h" // class's header file
#include "CUtil.h"
#include <iostream>
#include <sstream>
// class constructor
CBug::CBug()
{
}
// class destructor
CBug::~CBug()
{
}
CBug * CBug::CreateBug ( string Params )
{
#if 1
cout << "Param string:" << Params << endl;
#endif
if( Params.length() == 0 ) {
return NULL;
}
CBug * Bug = new CBug();
if ( Bug != NULL )
{
vector<string> s(5);
s = CUtil::StringSplit ( Params, " " ); // разбиваем строку с параметрами на отдельные строки
cout << s[0] << endl;
Bug->DevName = s[0];
Bug->Project = s[1];
Bug->ErrorDesc = s[3];
sscanf( s[2].c_str(), "%d", &(Bug->Id) );
cout << "id: " << Bug->Id << endl;
Bug->State = ACTIVE;
}
return Bug;
}
string CBug::GetDeveloper()
{
return DevName;
}
int CBug::GetState()
{
return State;
}
int CBug::GetId()
{
return Id;
}
void CBug::SetState ( BugState state )
{
State = state;
}
bool CBug::IsActive()
{
return ( State!=CLOSED );
}
string CBug::ToString() // для вывода пользователя
{
ostringstream out;
out << "Id: " << Id << " DevName: " << DevName << " Project: " << Project << " Desc: " << ErrorDesc << " State: " << State;
return(out.str());
}
精彩评论