初始化列表以一个冒号开始,接着是一个以逗号分隔的数据成员列表,每个成员变量后面跟一个放在括号中的初始值或表达式。
class Day
{
public:
//初始化列表
Day(int year, int month, int day)
: _year(year)
, _month(month)
, _day(day)
{}
private:
int _year;
int _month;
int _day;
};
每个成员只能初始化列表一次
类中以下成员,必须在列表初始化 |
---|
带引用的成员变量 |
const 成员变量 |
自定义类型成员变量(没有默认构造函数的类) |
构造函数不仅可以构造与初始化对象,对于单个参数或者除第一个参数无默认值其余均有默认值的构造函数,还具有类型转换的作用。
class Day
{
public:
Day(int a)
:_a(a)
{}
private:
int _a;
};
int main()
{
Day d1 = 1;
return 0;
}
//加上关键字explicit
class Day
{
public:
explicit Day(int a)
:_a(a)
{}
private:
int _a;
};
int main()
{
Day d1 = 1;//报错
//这里报错就是因为explicit修饰构造函数,禁止了单参构造函数类型转换的作用
Day d2(1);//正确
return 0;
}
class A
{
public:
A()
{
++_t;
}
A(const A & t)
{
++_t;
}
~A()
{
--_t;
}
static int GetACount()
{
return _t;
}
private:
static int _t;
};
int A::_t = 0;//正确初始化
int main()
{
A d1(1);//报错
//int A::_t = 0;//正确初始化
return 0;
}
class Day
{
//友元函数,声明
friend ostream& operator<<(ostream& out, const Day& d);
friend istream& operator>>(istream& in, Day& d);
public:
Day(int year=1, int month=1, int day=1)
: _year(year)
, _month(month)
, _day(day)
{}
private:
int _year;
int _month;
int _day;
};
//类外定义
istream& operator>>(istream& in, Day& d)
{
in >> d._year;
in >> d._month;
in >> d._day;
return in;
}
ostream& operator<<(ostream& out, const Day& d)
{
out << d._year << "-" << d._month << "-" << d._day << endl;
return out;
}
int main()
{
Day d1;
cin >> d1;
cout << d1 << endl;
return 0;
}
class Time
{
friend class Day; // 声明日期类为时间类的友元类,则在日期类中就直接访问Time类
//中的私有成员变量
public:
Time(int hour = 0, int minute = 0, int second = 0)
: _hour(hour)
, _minute(minute)
, _second(second)
{}
private:
int _hour;
int _minute;
int _second;
};
class Day
{
public:
Day(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;
}
private:
int _year;
int _month;
int _day;
Time _t;
};
友元类的关系不能传递,如果C是B的友元, B是A的友元,则不能说明C时A的友元。
friend 函数类型 operator 运算符(形参表)
{
//函数体
}
可以在类中声明友元函数,在类外定义。由于友元函数不是类的成员函数,在类外定义不需要加类名识别。
class Time
{
private:
static int k;
int h;
public:
class Day // B天生就是A的友元
{
public:
void foo(const A& a)
{
cout << k << endl;//OK
cout << a.h << endl;//OK
}
};
};
int Time::k = 1;
int main()
{
Time::Day b;
b.foo(Time());
return 0;
}
class A
{
public:
A(int a = 0)
:_a(a)
{
cout << "A(int a)" << endl;
}
~A()
{
cout << "~A()" << endl;
}
private:
int _a;
};
int main()
{
A aa1;//错误
// 不能这么定义对象,因为编译器无法识别下面是一个函数声明,还是对象定义
//定义匿名对象
A();//匿名对象生存周期只有这一行
A aa2(2);
return 0;
}
class A
{
public:
A(int a = 0)
:_a(a)
{
cout << "A(int a)" << endl;
}
~A()
{
cout << "~A()" << endl;
}
private:
int _a;
};
int main()
{
A aa1;//错误
// 不能这么定义对象,因为编译器无法识别下面是一个函数声明,还是对象定义
//定义匿名对象
A();//匿名对象生存周期只有这一行
A aa2(2);
return 0;
}
静态修饰匿名对象会延长匿名对象的声明周期