c++——结构与函数 const & 的优化

//const& 的优化
//结构与函数
struct MyPoint
{
    int x, y;
};
MyPoint MyAdd(MyPoint a, MyPoint b)
{
    MyPoint tempPos;
    tempPos.x = a.x + b.x;
    tempPos.y = a.y + b.y;
    return tempPos;
}
//这样做是不合适的:参数中为const& ,这样只用传4字节,不然要传8字节
//返回值类型为什么不用引用? 因为temPos为一个临时变量,调用完成后会被释放,不能引用一个无效内存
//类是公有属性的结构,结构是私有属性的类
struct MyPoint
{
    int x, y;
    MyPoint operator + (MyPoint const& srcPos) const;
};
MyPoint MyPoint::operator+ (MyPoint const& srcPos) const
{
    MyPoint tempPos;
    tempPos.x = x + srcPos.x;
    tempPos.y = y + srcPos.y;
    return tempPos;
}

MyPoint MyAdd(MyPoint const&a, MyPoint const &b)
{
    return a + b;
}

 

posted @ 2017-10-01 22:10  千面鬼手大人  阅读(399)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css