面向对象(中)
1.再谈构造函数
初始化列表
Date(int year = 0, int month = 1, int day = 1)
:_year(year)
,_month(month)
,_day(day)
{
}
有些成员变量必须在初始化列表初始化
1.const成员变量
2.引用成员变量
3.没有默认构造函数的自定义成员变量
成员变量声明的顺序就是其在初始化列表中初始化顺序,
隐式类型转换
explicit关键字
防止进行隐式类型转换
2.static成员
static成员变量,属于这个类所有对象,必须在类外面定义初始化
static 成员函数,没有this指针,函数中不能访问非静态成员
静态成员函数不能调用非静态成员函数,因为没有this指针
非静态成员函数可以访问静态成员函数
3.练习题
求1+…+N,不能用乘除法,for ,while,if ,else ,switch ,case等关键字
不能用递归
思路:类+static成员+数组
4.C++11 成员函数初始化
非静态成员变量可以在声明时给缺省值
class A
{
public:
A()
:a(2)
{
}
void Print()
{
cout << a << endl;
cout << b._b<< endl;
cout << p << endl;
}
private:
// 非静态成员变量,可以在成员声明时给缺省值。
int a = 10;
B b = 20;
int* p = (int*)malloc(4);
static int n;
};
int A::n = 10;
int main()
{
A a;
a.Print();
return 0;
}
5.友元
在类外面访问私有的成员变量
友元函数
class Date
{
friend ostream& operator<<(ostream& _cout, const Date& d);
friend istream& operator>>(istream& _cin, Date& d);
public:
Date(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& _cout, const Date& d)
{
_cout<<d._year<<"-"<<d._month<<"-"<<d._day;
return _cout;
}
istream& operator>>(istream& _cin, Date& d)
{
_cin>>d._year;
_cin>>d._month;
_cin>>d._day;
return _cin;
}
int main()
{
Date d1;
Date d2;
cin>>d1;
cout>>d2;
cout>>d1>>d2;//重载>>的返回值
cout<<d2<<endl;
return 0;
}
运算符重载,双目运算符默认有左右两个参数
自动输出不同类型的值,cout«函数重载
int x = 1;
double y = 11.1;
cout << x;
cout << y;
友元类
在Time类中加入Date友元类,Date即可访问Time类中所有成员
class Date;
// 前置声明员变量
class Time
{
friend class Date;
// 声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成
public:
Time(int hour, int minute, int second)
: _hour(hour)
, _minute(minute)
, _second(second)
{}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
public:
Date(int year = 1900, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day)
{}
void SetTimeOfDate(int hour, int minute, int second)
{
// 直接访问时间类私有的成员变量
_t._hour = hour;
_t._minute = minute;
_t.second = second;
}
}
内部类
一个类包含另一个子类
6.理解封装
高内聚,低耦合
一个类内部越紧密越好,类和类之间耦合度越低越好
匿名对象
Solution().Sum(10); //匿名对象声明周期只在这一行,过了这一行就调用析构函数
7.练习
计算所给日期是这一年的第几天