我正在创建课程,这样我就能更好地理解它们。当我创建一个类应该使用什么头文件和cpp?
答案 0 :(得分:3)
头文件用于类定义和实现的cpp文件。像这样:
<强> Test.h 强>
class Test
{
public:
void PrintHelloWorld(void);
};
<强> Test.cpp的强>
void Test::PrintHelloWorld(void)
{
cout << "Hej på dig världen!";
}
答案 1 :(得分:0)
这是一个非常基本的问题。您可能应该找到一本C ++教程或书籍来帮助您。
头文件具有类定义。
cpp文件具有类实现。
答案 2 :(得分:0)
头文件应该包含“#include”指令,常量定义和类方法的定义:构造函数,析构函数和方法。想想它就像定义类的接口一样。
Cpp应该包含实现。所以在cpp中你意识到你在.h文件中声明的所有内容。
以下是一个例子:
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());
}