学习笔记:学习静态定义对象和用new动态生成对象

参考书目:C/C++规范设计简明教程,P354

目的:学习静态定义对象和用new动态生成对象

第一步:建立工程,增加类TeacherInfo

头文件TeacherInfo.h

#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 
using namespace std;
class TeacherInfo
{
private:
	int fWorkNo;			//工号
	char fName[20];			//姓名
	char fPwd[20];			//密码
	char fAddress[40];		//家庭住址
public:
	void setFWorkNo(int workNo);	//设置工号
	int getFWorkNo();
	void setFName(const char *pName);		//设置姓名
	char *getFName();
	void setfPwd(const char *pPwd);		//设置密码
	char *getfPwd();
	void setFAddress(const char *pAddress);//设置家庭住址
	char *getFAddress();

	void display();
	TeacherInfo();
	~TeacherInfo();
	TeacherInfo(int workNo, const char *pName, const char *pPwd, const char *pAddress);

};

源文件TeacherInfo.cpp

#include "TeacherInfo.h"

void TeacherInfo::setFWorkNo(int workNo)	//设置工号
{
	fWorkNo = workNo;
}
int TeacherInfo::getFWorkNo()
{
	return fWorkNo;
}
void TeacherInfo::setFName(const char *pName)		//设置姓名
{
	strcpy(fName, pName);
}
char * TeacherInfo::getFName()
{
	return fName;
}
void TeacherInfo::setfPwd(const char *pPwd)		//设置密码
{
	strcpy(fPwd, pPwd);
}
char * TeacherInfo::getfPwd()
{
	return fPwd;
}
void TeacherInfo::setFAddress(const char *pAddress)//设置家庭住址
{
	strcpy(fAddress, pAddress);
}
char * TeacherInfo::getFAddress()
{
	return fAddress;
}

void TeacherInfo::display()
{
	cout << "工号是:" << fWorkNo << endl;
	cout << "姓名是:" << fName << endl;
	cout << "密码是:" << fPwd << endl;
	cout << "家庭住址是:" << fAddress << endl;
}

TeacherInfo::TeacherInfo(int workNo, const char *pName, const char *pPwd, const char *pAddress)
{
	fWorkNo = workNo;
	strcpy(fName, pName);
	strcpy(fPwd, pPwd);
	strcpy(fAddress, pAddress);
}
TeacherInfo::TeacherInfo()
{

}
TeacherInfo::~TeacherInfo()
{

}

第二步:主文件

//编写TeacherInfo类
#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 
#include "TeacherInfo.h"
using namespace std;
int main()
{
	cout << "Hello World!\n";
	TeacherInfo t1;
	t1.setFWorkNo(001);
	t1.setFName("黎明");
	t1.setfPwd("353535353");
	t1.setFAddress("北京市朝阳区凌云大道");
	t1.display();

	TeacherInfo *pt2 = new TeacherInfo(002,"李三","34343434","上海成功大道" );
	pt2->display();

	getchar();
}

运行结果如下:

学习笔记:学习静态定义对象和用new动态生成对象_第1张图片

你可能感兴趣的:(学习笔记:学习静态定义对象和用new动态生成对象)