2021-01-12 C++ Primer Plus 第十一章 使用类 复习题

复习题

1.使用成员函数为Stonewt类重载乘法运算符,该运算符将数据成员与double类型的值相乘。注意,用英石和磅表示时,需要进位。也就是说,将10英石8磅乘以2等于21英石2磅。

Stonewt Stonewt::operator*(double mult) const {
    Stonewt result;
    double res_pounds=stone*mult*Lbs_per_stn+pds_left*mult;
    result.stone=int(res_pounds)/Lbs_per_stn;
    result.pds_left=int(res_pounds)%Lbs_per_stn + res_pounds - int (res_pounds);
    result.pounds=res_pounds;
    return result;
}

2.友元函数和成员函数之间的区别是什么?

友元函数的原型在类中声明,在类外定义。成员函数在类中声明在类中定义。

3.非成员函数必须是友元才能访问类成员吗?

是的

4.使用友元函数为Stonewt类重载乘法运算符,该运算符将double值与Stone值相乘。

friend Stonewt operator*(double mult,const Stonewt &s);

Stonewt operator*(double mult,const Stonewt &s)
{
    Stonewt result;
    double res_pounds=s.stone*mult*s.Lbs_per_stn+s.pds_left*mult;
    result.stone=int(res_pounds)/s.Lbs_per_stn;
    result.pds_left=int(res_pounds)%s.Lbs_per_stn + res_pounds - int (res_pounds);
    result.pounds=res_pounds;
    return result;
}

5.那些运算符不能重载?

见书P316页

6.在重载运算符=、()、[]和->时,有什么限制?

只能通过成员函数进行重载。

7.为Vector类定义一个转换函数,将Vector类转换为一个double类型的值,后者表示矢量的长度。

operator double() const;
VECTOR::Vector::operator double() const{
     return mag;
};

你可能感兴趣的:(2021-01-12 C++ Primer Plus 第十一章 使用类 复习题)