gpt4 book ai didi

c++ - 在类中制作过滤器

转载 作者:行者123 更新时间:2023-11-28 03:33:23 26 4
gpt4 key购买 nike

我正在制作一个将多条记录保存在一个文件中的程序。我有不同的类代表不同的记录和另一个类,一个管理文件的模板类。

template <class DataType> class Table
{
public:
Table(const char* path);
bool add(const DataType& reg);
template <class FilterType> void print(const FilterType& filter) const
{
DataType reg;
...

if (reg == filter)
{
cout << reg << endl;
}

...
}


private:
const char* path;
};

class Student
{
public:
char cods[5];
char noms[20];
};

class Course
{
public:
char codc[5];
char nomc[20];
};

class Rating
{
public:
char cods[5];
char codc[5];
int prom;
}

我必须打印一个学生的评分,以及一门类(class)中所有学生的评分。像这样:

Table<Rating> trat("path.dat");
trat.print("A001") //print the ratings for student A001.
trat.print("C001") //print the students for course C001.

我们将不胜感激。

------编辑--------

好的,谢谢你的回答。我使用 cstrings 是因为我需要为类中的每个成员确定一个固定大小,因为我要将这些类写入文件。

我想要完成的是制作一个适用于任何类型或记录的模板类表。

我一直在想的是,我可以使用运算符重载来进行比较和输出。

像这样的东西:

class Student
{
public:
char cods[5];
char noms[25];

class CodsType
{
public:
CodsType(const string& cods) : cods(cods) {}
operator string() const { return cods; }
string cods;
};
};

class Course
{
public:
char codc[5];
char nomc[20];

class CodcType
{
public:
CodcType(const string& codc) : codc(codc) {}
operator string() const { return codc; }
string codc;
};

};

class Rating
{
public:
char cods[5];
char codc[5];
int prom;

bool operator==(const Course::CodcType& codc) const
{
return (this->codc == string(codc));
}
bool operator==(const Student::CodsType& cods) const
{
return (this->cods == string(cods));
}
};

然后:

Table<Rating> trat("path.dat");
trat.print(Student::CodsType("A001")) //print the ratings for student A001.
trat.print(Course::CodcType("C001")) //print the students for course C001.

但问题是我必须为每个过滤器做一个类。有更好的方法吗?

最佳答案

首先“你想做什么”?

模板和其他模板一样强大,但它们不会自己思考。您仍然需要了解您要做什么。

第一:您正在使用 C++ 进行编程。不要使用字符数组。使用标准::字符串。在大多数情况下,这就是您想要的,一些“文本”。

#include <string>    

class Student
{
public:
std::string cods;
std::string noms;
};

第二:reg == filter 是什么意思??? reg 和 filter 有不同的类型!他们不可能相等!如果您想比较它们,您需要定义“相等”的含义。

模板帮不了你。它们不是魔杖。你需要自己思考。如果您只将模板用于一种类型,则不需要模板。

#include <string>

class Table
{
Table(const std::string & path);
bool add(const Student & a); // add student to table
bool add(const Course & a); // add course to table
bool add(const Rating & a); // add rating to table
void filter(const std::string & str) const; // filter by string and print
};

void Table::filter(const std::string & str)
{
// find students, courses, and ratings here
}

您仍然需要弄清楚您要如何处理这 3 个结构。那还是要看你了

关于c++ - 在类中制作过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com