C++基础(13)类对象作为成员

13 篇文章 0 订阅

    类中的数据成员可以是基本数据类型,也可以是类对象这样的复合数据类型。     

    在一个类的数据成员中包含了另一个类的对象称为类的组合。这个被包含的对象称为对象成员或子对象。

以下实例将日期类的对象作为学生类的成员:

#include <iostream>
using namespace std;
class CDate  	///日期类
{	
private:
    int m_nYear;
	int m_nMonth;
	int m_nDay;
public:
	CDate(int nYear, int nMonth, int nDay); 
	int GetYear();
	int GetMonth();
	int GetDay();
};
CDate::CDate(int nYear, int nMonth, int nDay)
{
	m_nYear = nYear;
	m_nMonth = nMonth;
	m_nDay = nDay;
}
int CDate::GetYear()
{	return m_nYear;}

int CDate::GetMonth()
{	return m_nMonth;}

int CDate::GetYear()
{	return m_nDay;}

class CStudent 				//学生类
{	
    static unsigned long m_nCount; 	//学生人数
private:
	char *m_strName;			//姓名
	char *m_strID;			//编号
	char m_cSex;			//性别:'0':男  '1':女
	CDate m_Birthday; 			//出生日期(这个就是对象成员)
	char *m_strMajor;			//专业
public:
	CStudent(char* strName = "", char* strID = "", char cSex = '0', int nYear = 0, int nMonth = 0, int nDay = 0, char* strMajor = "");
	~CStudent();
	void SetName(char* strName);
……
public:
	void  SetBirthday(CDate Birthday);///操作对象成员的成员函数
	CDate GetBirthday();
}; 


int main()
{	
    ……
	cout<<"出生日期:"<<Student1.GetBirthday().GetYear()<<','
	<<Student1.GetBirthday().GetMonth()<<','<<Student1.GetBirthday().GetDay()
	<<"   ";调用对象成员的成员函数进行开发
    ....
}

小结:

(1)含有对象成员的类的形式可表示为:

class 类名

{

       …… 访问权限控制符:   

       类名1 对象成员1;     

       类名2 对象成员2;     

       ……     

       类名n 对象成员n;

}

(2)含有对象成员的类的构造函数可表示为以下形式:

类名::类名(形参表0):对象成员1(参数表1),对象成员2(参数表2),……

{

             ................

}   

 其中,“对象成员1(参数表1),对象成员2(参数表2),……”称为初始化表,用于对各个对象成员进行初始化。

 

 

 

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值