一分钟学会C++类的分层
我的第五天c++学习笔记
有子曰:“礼之用,和为贵。先王之道,斯为美;小大由之。有所不行,知和而和,不以礼节之,亦不可行也。”
以下纯手打,无复制
#include <iostream>
#include <string>
using namespace std;
class Birthday {
public:
int year; //年
int month; //月
int day; //日
//无参构造函数
Birthday() {}
//有参构造函数
Birthday(int year,int month,int day) {
this->year = year; //年
this->month = month; //月
this->day = day; //日
}
//显示函数
void showB() {
cout << year << "年" << month << "月" << day << "日" << endl;
}
};
class Person {
public:
string name;
string sex;
Birthday birthday;
//无参构造函数
Person() {}
//Person(string,string,int,int,int);
//有参构造函数
Person(string name,string sex,int year,int month,int day) {
this->name = name;
this->sex = sex;
this->birthday.year = year;
this->birthday.month = month;
this->birthday.day = day;
}
//显示函数
void showP() {
//birthday.showB();
//输出(姓名,性别,年月日)
cout
<< name
<< ","
<< sex
<< birthday.year
<< "年"
<< birthday.month
<< "月" << birthday.day
<< "日" << endl;
}
};
//定义构造函数(必须写第37行的声明构造函数)
//Person::Person(string name, string sex, int year, int month, int day) :birthday(year, month, day)
//{
// this->name = name;
// this->sex = sex;
//
//}
int main() {
//初始化对象---方法一
Person *person = new Person("码小余","男,",2001,3,8);
person->showP();
//初始化对象---方法二
/*Person pe;
pe.name = "码小余";
pe.sex = "男 ";
pe.birthday.year = 2001;
pe.birthday.month = 3;
pe.birthday.day = 8;
pe.showP();*/
}
以上运用了类的分层的知识,(自我感觉没什么用,但是为了应付考试,还是学学吧)
个人更加推荐类的继承,继承(代码简洁明了,派生类继承基类,多简单),具体请看我的另一篇学习笔记