美文网首页
More effective C++

More effective C++

作者: szn好色仙人 | 来源:发表于2018-06-20 20:48 被阅读0次
不要对数组使用多态。
  • 由于指向派生类和基类的指针,其各元素与数组首地址的偏移基本是不同的这就导致了当基类指针指向派生类数组时的寻址的bug
class CFahter
{
public:
    CFahter() : nValue(0) {}
    virtual ~CFahter() {}

private:
    int nValue;

public:
    const int GetValue() const { return nValue; }
};

class CChild : public CFahter
{
private:
    double aValue[10];
};

int main()
{
    CChild aChild[3] = {};
    CFahter* pFather = aChild;

    int aValue[] =
    {
        pFather[0].GetValue(),  //[0] = 0
        pFather[1].GetValue(),  //[1] = -858993460
        pFather[2].GetValue()   //[2] = -858993460
        //-858993460即0xCCCCCCCC
    };

    return 0;
}

谨慎定义类型转换函数

  • 慎重使用operator int()之类的隐式类型转换运算符
  • 为单参数构造函数加一个explicit
class CTest
{
public:
    CTest(int nValue) {}    
    operator int() { return 0; }
};

void Fun(CTest Test){}

int main()
{
    CTest Test(0);

    Fun(0);                 //令人不悦或者会感到意外的转换
    int nValue = 1 + Test;  //令人不悦或者会感到意外的转换
    return 0;
}

相关文章

网友评论

      本文标题:More effective C++

      本文链接:https://www.haomeiwen.com/subject/vzxfyftx.html