Chinaunix首页 | 论坛 | 博客
  • 博客访问: 373017
  • 博文数量: 57
  • 博客积分: 4020
  • 博客等级: 上校
  • 技术积分: 647
  • 用 户 组: 普通用户
  • 注册时间: 2007-07-17 15:57
文章分类

全部博文(57)

文章存档

2009年(22)

2008年(35)

我的朋友

分类: C/C++

2008-11-28 14:26:04

c++类入门class中重载成员函数
Author:yuexingtian
Date:  2008-11-28 Friday
/*class
重载成员函数
成员函数和普通函数一样,可以重载,规则也相同。
例如:在前面的日期类的基础上,增加一个string参数来设置年、月、日值的set成员函数:
*/
//=================yuexingtian-->begin====================== 
//重载成员函数
//==========================================================
#include
#include
#include
using namespace std;
//------------------------------- 
class Date
{
  private:
  int year,month,day;
  public:
  void set(int y,int m,int d);
  void set(string s);
  bool isleapyear();
  void print();
};
//------------------------------- 
void Date::set(int y,int m,int d)
{
  year=y;
  month=m;
  day=d;
}
//------------------------------- 
void Date::set(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());
}
//------------------------------- 
bool Date::isleapyear()
{
  return(year%4==0&&year%100!=0)||(year%400==0);
}
//------------------------------- 
void Date::print()
{
  cout<<setfill('0');
  cout<<setw(4)<<year<<'-'<<setw(2)<<month<<'-'<<setw(2)<<day<<'\n';
  cout<<setfill(' ');
}
//------------------------------- 
int main()
{
  Date d,e;
  d.set(2008,11,28);
  e.set("1986-09-03");
  if(d.isleapyear())
    d.print();
e.print();
return 0;
}
//==========================end==========================

运行结果:

分析:atoi(s.substr(0,4).c_str())是个什么意思?0和4代表什么, substr又代表什么?c.str呢?
1、首先,c++语言提供了两种字符串实现,例如:
    string s="12345";和char *s="12345";是不同的
2、s.substr(0,4)是从字符串s正向取4个字符,上面的s.substr(0,4)=“1234”;
3、atoi()将char*(字符串)转换成整形数值函数。 
    如:   
        char   *buf="1234";  
        int   i=atoi(buf);  
        //则i   =   1234; 
4、但是注意,上面的字符串是string类型的,而atoi只能把char*类型的字符串转化为整形,所以c.str实现的功能是把string转换为char*的
    结果atoi(s.substr(0,4).c_str())为整形1234
  上面其他的与这个类似:atoi(s.substr(5,2).c_str());中5和2代表从5个字符开始向后取2个字符。
atoi(s.substr(8,2).c_str());同上同理!
2008-11-28

tianyuexing
阅读(2676) | 评论(1) | 转发(0) |
0

上一篇:C++数据类型——向量(3)

下一篇:婚前婚后

给主人留下些什么吧!~~

chinaunix网友2010-06-03 22:47:50

谢谢啊!!