原贴如下:http://blog.youkuaiyun.com/longshengguoji/article/details/8507394#cpp
因为没有使用私有成员变量 ,所以我改成了私有成员变量的使用规则
但感觉代码有部分不妥,就最后一个而言进行如下修改
两个类 包含两个.h和两个.cpp 最后有个主程序cpp
分别写的。
#pragma once
#include <string>
#include <iostream>
using std::string;
class CStudent
{
public:
CStudent();
~CStudent();
public:
CStudent(string strNO, string strName, string strSex, string strDate);
void Display();
string StrNO();
private:
string m_strNO;
string m_strName;
string m_srtSex;
string m_strDate;
};
#pragma once
#include "Student.h"
#include <vector>
using std::vector;
class CStudCollect
{
public:
CStudCollect();
~CStudCollect();
public:
void Add(CStudent &s);
CStudent*Find(string strNO);
private:
vector<CStudent> m_vStud;
};
#include "stdafx.h"
#include "Student.h"
#include <iostream>
using std::cout;
using std::endl;
CStudent::CStudent()
{
}
CStudent::~CStudent()
{
}
CStudent::CStudent(string strNO, string strName, string strSex, string strDate) :m_strNO(strNO), m_strName(strName), m_srtSex(strSex), m_strDate(strDate){}
void CStudent::Display()
{
cout << m_strNO << "\t";
cout << m_strName << "\t";
cout << m_srtSex << "\t";
cout << m_strDate << "\t";
}
string CStudent::StrNO()
{
return m_strNO;
}
#include "stdafx.h"
#include "StudCollect.h"
#include "Student.h"
CStudCollect::CStudCollect()
{
}
CStudCollect::~CStudCollect()
{
}
void CStudCollect::Add(CStudent &s)
{
m_vStud.push_back(s);
}
CStudent* CStudCollect::Find(string strNO)
{
bool bFind = false;
int i;
for ( i = 0; i < m_vStud.size(); i++)
{
CStudent& s = m_vStud.at(i);
if (s.StrNO() == strNO) //对象不能访问私有成员函数,所以s.m_StrNo 这种写法是错的。只能写个函数返回私有成员值。
{
bFind = true;
break;
}
}
CStudent*s = NULL;
if (bFind)
{
s = &m_vStud.at(i);
}
return s;
}
// vector4.0.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include "Student.h"
#include "StudCollect.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CStudent s1("1001", "zhangsan", "boy", "1998-10-10");
CStudent s2("1002", "lisi", "boy", "1988-8-25");
CStudent s3("1003", "wangwu", "boy", "1989-2-14");
CStudCollect s;
s.Add(s1);
s.Add(s2);
s.Add(s3);
CStudent *ps = s.Find("1102");
if (ps)
{
ps->Display();
}
return 0;
}