目录
本篇记录使用类的相关知识:
- 运算符重载
- 转换函数
运算符重载
运算符重载属于C++里面的多态,可用于用户自定义类型。
eg:
class Time
{
private:
int hours;
int minutes;
public:
Time operator+(const Time & t)const;
}
Time Time::operator+(const Time &t) const
{
Time sum;
sum.minutes = minutes+t.minutes
return sum
}
注:(1)运算符重载包括两种,成员函数重载(类成员函数)和非成员函数重载(友元函数,以访问类成员)。
(2)运算符重载参数个数不变,如对+重载后,参数仍为两个。
(3)对于双目运算符,成员函数参数个数为1,因为默认隐参数是对象本身。非成员函数参数为2。
常用重载运算符<<示例:
ostream & operator<<(ostream & os, const time &t)
{
os << t.hour<<"hours,"<<t.minute<<"minutes"<<endl;
return os;
}
模板:
ostream & operator<<(ostream &os,const c_name &obj)
{
os<<...;
return os;
}
//说明:函数参数为引用是因为此时的cout传入的是他本身而不是其拷贝,是必须的;
函数返回为引用的含义是返回的仍是传入参数本身,从而可以为后续os<<..<<..铺垫。
转换函数
数值转换为类(构造函数)
eg:
class person
{
private:
double weight;
double height;
public:
person();
person(double m_weight);
}
person::person()
{
weight = 0;
height = 0;
}
person::person(double m_weight)
{
weight = m_weight;
height = 123.2;
}
在类的定义中,构造函数使用数值类型作为参数,则可以用于转换。
person p;
p = 11.2;//完全可以
注:只有构造函数只有一个参数时才可以进行转换,或者其他参数都提供默认值。如:
person::person(double a,double b = 11.2);
p = 11.2;//完全可以
可以进行二次类型转换,如上述,可以用int参数代入,int先转换为double再转换为类对象。
关闭隐式转换:
声明构造函数时使用explicit关键字,则只能使用显式强制转换。(在头文件声明即可,cpp不需要)
//构造函数未使用explicit时:
p = 11.2;//可以
//使用后:
p = 11.2;//error
p = person(11.2);//correct
p = (person)11.2;//correct
注:所有转换都必须避免二义性,如上述int转换为double,如果还存在long类型构造函数,则转换失败。
类型转换为值
使用转换函数实现。注意转换函数必须是类方法,不能指定返回类型,不能有参数。
模板:
operator typename();
eg:
class person
{
private:
double weight;
double height;
public:
person();
operator double();
operator int();
}
person::operator int()
{
return int(weight+0.5);
}
person::operator double()
{
return height;
}
用法:
person p1(1.1,1.2);
double a = p1;//隐式转换
与构造函数转换相同,可以用explicit来实现只能显式转换;二义性原则不能变。