类对象作为数据成员

代码

1、编写.h文件

#include <iostream>
#include <string>
using namespace std;

class Date
{
public:
    //有参构造
    Date(int year = 0, int month = 0, int day = 0);
    //拷贝构造函数
    Date(Date &birth);
    //析构函数
    ~Date(){}
    //输出出生日期
    void showBirth();


private:
    int m_year;
    int m_month;
    int m_day;
};

class Student
{
public:
    /*
     * 其他类对象作为本类数据成员时,其他类对象构造函数先调用,再调用本类构造函数,析构函数调用顺序相反
     */
    //有参构造
    Student(string name, int age, char gender, Date birth);
    //析构函数
    ~Student(){}
    //拷贝构造函数
    Student(Student &stu);
    //输出学生信息
    void showStudent();

private:
    string m_name;      //姓名
    int m_age;          //年龄
    char m_gender;      //性别
    Date m_birth;       //出生日期
};

2、编写.cpp文件

#include "../Headers/test.h"

Date::Date(int year, int month, int day) {
    m_year = year;
    m_month = month;
    m_day = day;
}

void Date::showBirth() {
    cout<<"出生日期:"<<m_year<<"."<<m_month<<"."<<m_day<<endl;
}

Date::Date(Date &birth)
{
    m_year = birth.m_year;
    m_month = birth.m_month;
    m_day = birth.m_day;
}

Student::Student(string name, int age, char gender, Date birth):m_birth(birth)
{
    m_name = name;
    m_age = age;
    m_gender = gender;
}

Student::Student(Student &stu)
{
    m_name = stu.m_name;
    m_age = stu.m_age;
    m_gender = stu.m_gender;
}

void Student::showStudent()
{
    cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
    cout<<"姓名:"<<m_name<<endl;
    if(m_gender == 'f')
        cout<<"性别:"<<"女"<<endl;
    else
        cout<<"性别:"<<"男"<<endl;
    cout<<"年龄:"<<m_age<<endl;
    m_birth.showBirth();
    cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
}

3、编写main.cpp文件

#include "test.cpp"

int main() {
    int year, month, day;             //出生日期
    string name;                    //姓名
    char gender;                    //性别
    int age;                        //年龄

    cout << "请输入出生日期:";
    cin >> year >> month >> day;
    cout << "请输入姓名:";
    cin >> name;
    cout << "请输入年龄:";
    cin >> age;
    cout << "请输入性别(f(女)/m(男)):";
    do
    {
        cin>>gender;
    }while(gender != 'f' && gender != 'm');


    Date birth(year, month, day);

    Student stu(name, age, gender, birth);
    stu.showStudent();
}

运行

在这里插入图片描述

Clion控制台乱码解决方案

在这里插入图片描述
在这里插入图片描述

在cmakelist.txt添加如下代码

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fexec-charset=GBK")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值