学习笔记:类的建立和使用

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

第一步:建立基于win32控制台的程序

第二步:增加Person.h

//#pragma once
#ifndef PERSON_H
#define PERSON_H

class  Person
{
public:
	 Person();
	~ Person();
private:
	int fId;
	char fName[20];
public:
	void setFid(int id);
	void setFName(const char *pName);	//这里必须用常指针
	void display();

};

#endif





第三步:编写Person.cpp

#define _CRT_SECURE_NO_WARNINGS
#include "Person.h"
#include <string.h>
#include <iostream>
using namespace std;
Person::Person()
{
}

Person::~Person()
{
}
void Person::setFid(int id)
{
	fId = id;
}
void Person::setFName(const char *pName)	//这里必须用常指针
{
	strcpy(fName, pName);
}
void Person::display()
{
	cout << fId << fName;
}

第四步:编写主文件

//类和对象示例
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "Person.h"
using namespace std;
int main()
{
	cout << "Hello World!\n";
	Person p1;
	p1.setFid(2);
	p1.setFName("郭靖");
	p1.display();
	Person p2;
	p2.display();		//显示为乱码




	getchar();
}

运行结果如下:

发布了34 篇原创文章 · 获赞 1 · 访问量 743

猜你喜欢

转载自blog.csdn.net/qq_41708281/article/details/104161016