- 模板优化代码量
背景:
有些代码,比如管理员的查看信息功能,我想优化成用模板,可以减少代码。但是发现在输出的时候,学生和老师统一性就更高了,导致输出提示只能是id号,而不是学号、职工号。 还有就是,我用模板前,本想用identity来放在输出函数里面,输出信息,但是想了下,这样会改变类的结构,因为id号只有学生和老师有,管理员没得,该了化其他地方可能会出问题,牵一发而动全身,划不来。
理解:
改变了需求,所以在开发过程中,做一些优化结构但又不是那么必要的优化时候,要考虑多个方面,最好是不做不必要的优化。
//输出模板 templatevoid printPerson(T& t) { cout << "id号(学号/职工号): " << t.id << "tt用户名:" << t.m_Name << "tt用户密码:" << t.m_Psw << endl; } //查看账号 void Manager::showPerson() { cout << "请选择查看内容:" << endl; cout << "1.查看所有学生" << endl; cout << "2.查看所有老师" << endl; int select; cin >> select; if (select == 1) { cout << "n所有的学生信息如下:nn"; for_each(vStu.begin(), vStu.end(), printPerson ); } else { cout << "n所有的老师信息如下:nn"; for_each(vTea.begin(), vTea.end(), printPerson ); } system("pause"); system("cls"); }
- 压入容器的对象和源对象:
背景:
将一个对象压入vector后,改变这个对象的属性,vector会改变不?
理解:
如图,vector的t,和原来t不是一个东西
#include#include #include using namespace std; class Temp { public: Temp(int a, int b) { this->a = a; this->b = b; } int a; int b; }; void test() { Temp t(1,2); cout << "t :" << t.a << endl; vector v; v.push_back(t); t.a = 3; cout << "new t: " << t.a << endl; cout << "vector t: " << v[0].a << endl; } int main() { test(); return 0; }
- c++字符串转化 数
用 atoi(),先转化c风格字符,再转化int
atoi( of.m_oderData[i]["stuID"].c_str() )疑惑
为什么被注释的可以在管理员界面输出vector里面的值,而没注释的输出不了?
//为什么不可以?
Student stu;
Student* s2;
while (ifs >> stu.id && ifs >> stu.m_Name && ifs >> stu.m_Psw)
{
s2 = new Student (stu.id, stu.m_Name, stu.m_Psw);
vStu.push_back(*s2);
}
另外测试了一下以下代码,却又可以输出
#include#include #include using namespace std; class Temp { public: Temp(int a, int b) { this->a = a; this->b = b; } int a; int b; }; class MyPrint { public: void operator() (Temp t) { cout << "值:" << t.a << endl; } }; void test() { Temp * t1; vector vt; int i = 5; while(i--) { t1 = new Temp(i, i*2); vt.push_back(*t1); } for_each(vt.begin(), vt.end(), MyPrint()); } int main() { test(); return 0; }



