C++编程学习笔记 week7

本文详细介绍了C++编程中构造函数与析构函数的使用,包括日期类、长方形类、时间类的构造函数应用,斐波那契数列动态数组的实现,以及圆类和学生类中动态内存的管理。通过实例分析了构造函数的默认参数、拷贝构造函数的深浅拷贝以及析构函数在内存释放中的作用。
摘要由CSDN通过智能技术生成

构造函数与析构函数

6.1 日期类用法–几种构造函数定义

定义一个日期类,该类数据成员有年、月、日3个私有数据。公有成员函数按指定格式输出日期,构造函数有4个:无参构造函数、带普通参数的构造函数、带字符串参数的构造函数、自定义拷贝构造函数。在主函数中通过构造函数进行对象初始化,以年-月-日格式输出日期。要求在类中补充4个构造函数定义。

#include <iostream>
#include <stdlib.h>//string类
using namespace std;
class Date
{
public:
    void Print()//输出
    {
        cout<<"日期是"<<year<<"-"<<month<<"-"<<day<<endl;
    }
private:
    int year;
    int month;
    int day;
public:
    Date()//无参
    {
        year=0;
        month=0;
        day=0;
    }
    
    Date(int a,int b,int c)//普通参数
    {
        year=a;
        month=b;
        day=c;
    }
    
    Date(string s)//带字符串参数
    {
        year=atoi(s.substr(0,4).c_str());
        month=atoi(s.substr(5,2).c_str());
        day=atoi(s.substr(8,2).c_str());
       
    }
    
    Date(Date &r)//自定义拷贝构造参数
    {
        year=r.year;
        month=r.month;
        day=r.day;
    }
    
    
};//类的定义结束



int main()
{
        Date a1(2012,2,27);//调用带普通参数的构造函数
        a1.Print();
        
        Date a2("2014-02-23");//调用带字符串参数的构造函数
        a2.Print();
        
        Date a3;//调用无参构造函数
        a3.Print();
        
        Date a4(a1);//调用拷贝构造函数  此句与Date a4=a1;等价
        a4.Print();
        return 0;
}

year=atoi(s.substr(0,4).c_str())

  • atoi()函数
    原型为: int atoi(char *str),用途是将字符串转换成一个整数值,str是待转化成整数值的字符串.成功责返回转化后的整数值,失败返回0.

  • substr()函数
    原型为:basic string::substr(string,start,length),也可把string移到外面,为string &a,a.substr(start,length),其中a是待截取的字符串,start表示从截取开始的前一位,length表示截取长度,例如string &a=“hello world”,则a.substr(6,5)=world.

  • c_str()函数
    原型为:const char c_str(),如果要将string对象,转化为char对象,c_str()提供了这样一种方法,它返回一个客户程序可读不可改的指向字符数组的指针。所以year=atoi(s.substr(0,4).c_str())的作用就是,截取string型的对象s,并转化为char*对象,然后将此字符串转换成一个整数值,赋值给year(year是int型).

Date(Date &r)
{
year=r.year;
month=r.month;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值