[凡鸽鸽]《实验报告04》 类和对象(一)

这篇博客介绍了如何使用C++创建一个日期类`Date`,包括设置和显示日期,以及比较日期是否相等的方法。此外,还定义了一个`Person`类,用于存储个人姓名、生日和性别,并实现了相应的方法来更新和展示这些信息。在测试项目中,用户可以输入姓名、生日和性别,程序将输出个人信息。
摘要由CSDN通过智能技术生成

《实验报告04》

类和对象(一)

代码使用说明:

在新建项目里对应的 头文件 或 源文件 里,新建对应的文件,并把代码复制进去即可。

创建效果如图:

创建

代码如下:
//1、stdafx.h头文件
#pragma once
#include <iostream>
#include <string>
using namespace std;

// 2、Date.h头文件
//日历类Date.h头文件
#pragma once
// 日历类
class Date
{
//public:
protected:
	// 月
	int month;
	// 日
	int day;
	// 年
	int year;
public:
	// 属性月month, 日day, 年year的值分别更新为接口Month,Day,Year的值
	void Update(int Month, int Day, int Year);
	// 在屏幕插入属性月month, 日day, 年year的值
	void Show(void);
	//若日历(*this)与另一日历anotherDay
    //不是同一天, 则返回true, 否则, 返回false
	bool notEqual(Date anotherDay);
};

// 3、Date.cpp文件
// 7、日历类Date.cpp源文件
// 包含StuAfx.h头文件
//#include "StdAfx.h"
// 包含日历类date.h头文件
#include <iostream>
#include "Date.h"
using namespace std;
// 创建日历

// 属性月month, 日day, 年year的值分别更新为接口Month,Day,Year的值
void Date::Update(int Month, int Day, int Year)
{
	// 属性月month更新为接口Month的值
	month = Month;
	// 属性日day更新为接口Day的值
	day = Day;
	// 属性年year更新为接口Year的值
	year = Year;
}

// 在屏幕插入属性月month, 日day, 年year的值
void Date::Show(void)
{
	// 按日期格式, 以"-"分隔, 在屏幕插入属性月month, 日day, 年year的值
	cout <<month << "-" <<day << "-" << year;
}

//若日历(*this)与另一日历anotherDay
//不是同一天, 则返回true, 否则, 返回false
bool Date::notEqual(Date anotherDay)
{
	// 若year与anotherDay.year不同, 或month与anotherDay.month不同, 
	// 或day与anotherDay.day不同, 则返回true, 否则, 返回false
	return (year != anotherDay.year) || (month != anotherDay.month) || (day != anotherDay.day);
}


// 4、Person.h头文件
#pragma once
#include "stdafx.h"
#include "Date.h"
class Person
{
	private:
		string Name;
		Date Birthday;
		string Sex;
public:
		void Update(string name, Date birthday, string sex);
		void Speak();
};

// 4、Person.cpp文件
#include "Person.h"

void Person::Update(string name, Date birthday, string sex)
{

	Name = name;
	Sex = sex;
	Birthday = birthday;
}

void Person::Speak()
{
	cout << endl << "我的姓名是:" << Name << ", 性别为:" << Sex << ", 生日是:";
	Birthday.Show();
	cout << endl;
}

// 6、项目测试源文件
#include "stdafx.h"
#include "Person.h"
#include "Date.h"
int main()
{
    system("color F0");
    string name; string sex = "";
    Person p1;
    int Month,  Day,  Year; Date birthday;

    cout << "请输入姓名Name:"<< endl; cin >> name ;

    cout << "生日Birthday(按此格式:月-日-年 输入):" << endl; 
        cin >> Month; getchar();
        cin >> Day;   getchar();
        cin >> Year; 

    cout << "性别Sex:" << endl; cin >> sex;

    birthday.Update(Month, Day, Year);
    p1.Update(name, birthday, sex);
    p1.Speak();
}
项目测试运行结果如图:

测试

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值