【发布时间】:2017-09-16 05:40:44
【问题描述】:
我有一个头文件,其中一个功能是:
template <class Pclass, class Pfunc1, class Pfunc2> //Capable of multiple outputs per call
int view_recordT(Pclass Object_1, char Compare_char, char* file_1, Pfunc1 show_tablular, Pfunc2 get_compare_char) { //Search function to find records
int currID, records_read;
bool run=false;
ifstream fin;
fin.open(file_1, ios::binary); //Opens the file again
if(!fin) { //Checks whether the file file_1 exists or not
cout<<"File not found!";
return(-1);
}
while(fin>>currID && fin.read((char*)& Object_1, sizeof(Object_1))) //Reads a record into stream until it can't
if(Object_1.get_compare_char() == Compare_char) {
records_read++;
cout<<endl; AddColumn(currID,7); Object_1.show_tablular();
run=true;
}
fin.close();
if(run==false) //Returns a false flag (0) if records not found
return int(run);
return records_read; //Otherwise, the number of records read is returned
}
注意: bool 是一个枚举,因为 TurboC++ 不支持布尔值 true/false。 enum bool { false, true }
我一直在使用 TurboC++,因为我的学校很笨,我们甚至没有被教过模板,所以这就是我问这个可能很愚蠢的问题的原因。
Test.cpp
class Test_Class {
int int_member;
char char_member[20], group_ID;
float float_member;
static int currID; //Static Var for Record Keeping in Files
public:
Test_Class();
void enter();
void show_tablular();
char get_group_id();
static int ret_ID() { //Repeative calls are recorded & count is returned.
return ++currID;
}
};
int Test_Class::currID = 0;
void main() {
clrscr();
Test_Class Object, Object1;
char file[20];
strcpy(file,"lib_Test.dat");
int run, records_read=0;
char group_ID;
cout<<"Enter the Group ID to be searched for: ";
cin>>group_ID;
run = view_recordT(Object, group_ID, file, &Test_Class::show_tablular, &Test_Class::get_group_id);
if(run == false)
cout<<"\nRecord not found!";
cout<<"\n Total of "<<records_read<<" records have been read!";
getch();
}
这里的目标是将一个对象传递给 view_recordT() 和来自 test.cpp 的类方法的地址,以便 view_recordT() 可以执行语句,就好像它是 Test_Class 的成员一样。 但我收到一个错误:
get_compare_var() 不是 Test_Class 的成员
问题
如何修改 view_recordT() 函数,使其完全独立于用于读取文件的类运行?
【问题讨论】:
标签: c++ templates generic-programming turbo-c++