对象的使用

对象数组与对象指针

1,初始化对象数组

Date dt[3] = { Date(2003,8,9),Date(2022,2,8) };

dt[2]使用构造函数提供的默认值

2,引用成员的两种方法

对象数组名+下标)->成员名或*(数组名+下标).成员名

对象指针 指针变量名->            或(*指针变量名).

对象引用

#include <iostream>
#include"classdate.h"
using namespace std;
Date& fun(Date& pdate)
{
    pdate.modify(2022, 2, 10);
    pdate.display();
    return pdate;
}
int main()
{
    Date dt1(2021);
    dt1.display();
    dt1.modify(2022,2,9);
    dt1.display();
    Date tdate = fun(dt1);
    tdate.display();
    cout << endl;
    fun(dt1) = Date(2003, 2, 2);
    dt1.display();
    tdate.display();
    cout << endl;
    fun(tdate) = Date(2003, 2, 2);
    dt1.display();
    tdate.display();
    return 0;
}

头文件 "classdate.h"见下,插入方法:

VS版本Visual Studio 2022,右侧源文件右键单击 添加 新建项 头文件(.h)

#pragma once
int i = 0;
int j = 0;
class Date
{
	int year;
	int month;
	int day;
public:
	Date(int y = 2022, int m = 2, int d = 8)
	{
		year = y;
		month = m;
		day = d;
		std::cout << "构造" << std::endl;
	}
	~Date()
	{
		std::cout << "析构" << std::endl;
	}
	void display()
	{
		std::cout << year << " " << month << " " << day << std::endl;
	}
	void modify(int yy, int mm, int dd)
	{
		year = yy;
		month = mm;
		day=dd;
	}
};

运行结果如下 

 

22行构造无名对象修改引用,赋值给dt1,相当于dt1=Date(2003,2,2)但tdate值不改变,对比26行修改tdate后dt1值也改变

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值