在编写 C++ 项目时,经常会把整个项目分为多个文件来编写,每个文件作为一个独立的函数模块。
对于类的定义可将其放在头文件(例如:MyHeader.h)中,而在其他的每个文件中直接 #include “MyHeader.h” 即可。
例如:
// MyHeader.h
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
using namespace std;
struct sample {
int int_id;
vector <double> vecDou_attribute;
int int_type;
};
class totalData {
public:
void Void_rawData_read ( int int_attributeNum, char chaArr_filePath[] );
void temp();
private:
vector <struct sample> vecStc_rawData;
vector <struct sample> vecStc_trainData;
vector <struct sample> vecStc_validateData;
vector <struct sample> vecStc_testData;
};
上述代码中并没有定义类中的函数,如果要在类的外部使用范围解析运算符 :: 定义该函数的话,则函数定义不能写在头文件中。
如果将类的成员函数定义写在了头文件中,则当在其他文件中 include 头文件时,会出现重复定义函数的错误。
示例
// MyHeader.h
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
using namespace std;
struct sample {
int int_id;
vector <double> vecDou_attribute;
int int_type;
};
class totalData {
public:
void Void_rawData_read ( int int_attributeNum, char chaArr_filePath[] );
void temp();
private:
vector <struct sample> vecStc_rawData;
vector <struct sample> vecStc_trainData;
vector <struct sample> vecStc_validateData;
vector <struct sample> vecStc_testData;
};
void totalData::Void_rawData_read( int int_attributeNum, char chaArr_filePath[] )
{
ifstream ifstream_myfile ( chaArr_filePath );
if ( !ifstream_myfile.is_open() ) {
cout << "未成功打开文件!" << endl;
exit;
}
else {
string str_currentLine;
getline( ifstream_myfile, str_currentLine ); // 读取第一行属性名称,不做处理
while ( getline( ifstream_myfile, str_currentLine ) ) {
cout << str_currentLine << endl;
}
}
return;
}
void totalData::temp()
{
for ( int i=0; i<100; i++ )
cout << i << "\t";
return;
}
// main 函数
#include "MyHeader.h"
int main()
{
totalData a1;
a1.temp();
return 0;
}
这样会报错说函数重复定义。
正确做法:
头文件中只定义类
// MyHeader.h
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
using namespace std;
struct sample {
int int_id;
vector <double> vecDou_attribute;
int int_type;
};
class totalData {
public:
void Void_rawData_read ( int int_attributeNum, char chaArr_filePath[] );
void temp();
private:
vector <struct sample> vecStc_rawData;
vector <struct sample> vecStc_trainData;
vector <struct sample> vecStc_validateData;
vector <struct sample> vecStc_testData;
};
在其他文件中定义类的成员函数:
#include "MyHeader.h"
void totalData::Void_rawData_read( int int_attributeNum, char chaArr_filePath[] )
{
ifstream ifstream_myfile ( chaArr_filePath );
if ( !ifstream_myfile.is_open() ) {
cout << "未成功打开文件!" << endl;
exit;
}
else {
string str_currentLine;
getline( ifstream_myfile, str_currentLine ); // 读取第一行属性名称,不做处理
while ( getline( ifstream_myfile, str_currentLine ) ) {
cout << str_currentLine << endl;
}
}
return;
}
void totalData::temp()
{
for ( int i=0; i<100; i++ )
cout << i << "\t";
return;
}
int main()
{
totalData a1;
a1.temp();
return 0;
}
程序可正确运行: