第七章 类和对象介绍
1. 函数名以小写字母开头,之后单词大写字母开头;用户定义类以大写字母开头,之后也是大写字母开头
2. 接口与实现的分离
3. 局部变量声明在函数体中,只作用于当前函数,数据成员对类的所有成员函数均可访问
4. String类的实现
简单实现-参考
http://rsljdkt.iteye.com/blog/770072
第八章 类的深入剖析
1.等价于#program once
#ifndef TIME_H //如果没有定义
#define TIME_H
……
#endif
2.析构函数-在系统回收对象的内存之前执行扫尾工作,使得内存可以重新用于存储新的对象,并不释放对象的存储空间
3.Time类-一个最基本的类
1.h
#ifndef TIME_H
#define TIME_H
class Time
{
public:
Time(int =0,int =0,int =0);//生命Time构造函数
void setTime(int ,int ,int);
void setHour(int);
void setMinute(int);
void setSecond(int);
int getHour();
int getMinute();
int getSecond();
void printStandard();
private:
int hour;
int minute;
int second;
};
#endif
1.cpp
#include <iostream>
#include "1.h"
using namespace std;
Time::Time(int hr,int min,int sec)
{
setTime(hr,min,sec);
}
void Time::setTime(int h,int m,int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}
void Time::setHour(int h)
{
hour=(h>=0&&h<24)?h:0;//初始化
}
void Time::setMinute(int m)
{
minute=(m>=0&&m<60)?m:0;
}
void Time::setSecond(int s)
{
second=(s>=0&&s<60)?s:0;
}
int Time::getHour()
{
return hour;
}
int Time::getMinute()
{
return minute;
}
int Time::getSecond()
{
return second;
}
void Time::printStandard()
{
cout<<getHour()<<": "<<getMinute()<<": "<<getSecond()<<endl;
}
2.cpp
#include <iostream>
#include "1.h"
using namespace std;
void main()
{
Time t1;
Time t2(2);
t1.printStandard();
t2.printStandard();
}
3.友元函数和类friend
在类的作用域以外定义却具有访问类的非public成员的权限,单独的类/函数都可以被声明为另一个类的友元。在类的定义中函数原型前+friend
#include <iostream>
using namespace std;
class Count
{
friend void setX(Count &,int);//友元声明
public:
Count()
:x(0)
{
}
void print() const
{
cout<<x<<endl;
}
private:
int x;
};
//在类的作用域以外定义
void setX(Count &c,int val)
{
c.x=val;
}
void main()
{
Count counter;
counter.print();//0
setX(counter,8);
counter.print();//8
}
4.this指针-访问自己的地址
this->x == (*this).x
5.使用new,delete对内存进行动态管理
Time *timePtr;
timePtr=new Time;
……
delete timePtr;
int *array=new int[10];//可在类的构造函数中
……
delete [] array;//可在类的析构函数中
6.static 类成员
只在类的作用域内起作用,类的private、protected的static成员通常通过类的public成员函数或者类的友元访问
当没有任何类的对象存在时,类的static成员依然存在
7.容器类container和迭代器iterator
参考详细介绍http://blog.csdn.net/nancy_m/article/details/8073013