C++面向对象高级编程(下)第一周-Geekband

勿在浮沙筑高台

革命尚未成功,同志仍需努力


<h1> Conversion Function</h1>
class  Fraction
{
public:
    Fraction(int n, int den = 1) : m_fenzi(n), m_fenmu(den){}
    operator double() const
    {
        return (double)(m_fenzi/m_fenmu);
    }
 
private:
    int m_fenzi;        //分子
    int m_fenmu;    //分母
 
};

operator double 属于转换函数, 这里不能设定传入值和传出值

Fraction f(4,5);
double d = 4 + f;
编译器查找顺序:
1,找有没有全局函数operator+
2,找Faction有没有operator double

其中double还可以有:
String,int ,float 所以这里的转换并不局限于任何基本类型, 任何type只要之前出现过,编译器就会认得该type.
  





<h1>  non-explicit-one-argument ctor</h1>
之前的例子:

class  Fraction
{
public:
    Fraction(int n, int den = 1) : m_fenzi(n), m_fenmu(den){}
    Fraction operator +(const Fraction& f) const
    {
        return ...;
    }
 
/*
    operator double() const
    {
        return (double)(m_fenzi/m_fenmu);
    }
*/
private:
    int m_fenzi;        //分子
    int m_fenmu;    //分母
 
};


//使用:
Faction f(3,5);
Faction d = f + 4; //?


Faction d = f + 4 
编译器查找顺序:
1, Fraction 有没有operator+(int) 
2, 调用 non-explicit ctor 将 4 转为 Fraction(4) , 然后调用operator+(Fraction)

但: 
当加入operator double()的时候在调用实例:
Faction d = f + 4  
就会发生二义性. 
1, 将4转为Fraction(4)
2, 将f转为double
所以这里将会出错. 



<h1>  explicit-one-argument ctor</h1>
class  Fraction
{
public:
    explicit Fraction(int n, int den = 1) : m_fenzi(n), m_fenmu(den){}
    Fraction operator +(const Fraction& f) const
    {
        return ...;
    }
 
/*
    operator double() const
    {
        return (double)(m_fenzi/m_fenmu);
    }
*/
private:
    int m_fenzi;        //分子
    int m_fenmu;    //分母
 
};


//使用:
Faction f(3,5);
Faction d = f + 4; //?


这里explicit将会限制编译器,不要随便转化.









<h1>pointer-like classes </h1>智能指针
迭代器

操作符重载: 
operator*()
operator->()
operator++()
operator--()
让类更像指针一样操作

//============================================================================================//
这周深刻了解了包含头文件的< >与" "的区别
<span style="font-family: 微软雅黑; font-size: 14px; line-height: 21px; widows: auto;">     区别在编译器在搜索头文件时的顺序不同。</span><div style="font-family: 微软雅黑; font-size: 14px; line-height: 21px; widows: auto;">    </div><div style="font-family: 微软雅黑; font-size: 14px; line-height: 21px; widows: auto;">    < >表示从系统目录下开始搜索,然后再搜索PATH环境变量所列出的目录,不搜索当前目录;<div style="background-color: inherit;">    <br style="background-color: inherit;" /></div><div style="background-color: inherit;">    " "表示从当前目录搜索,然后是系统目录和PATH环境变量所列出的目录。<br style="background-color: inherit;" /></div><div style="background-color: inherit;"><br style="background-color: inherit;" /></div><div style="background-color: inherit;">    所以如果我们知道头文件在系统目录下,就可以直接用< >  , 以加快搜索速度。</div></div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值