码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-10-01 23:01:55      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:私有   return   结构   为什么   amp   返回值   不用   优化   pre   

//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;
}

 

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

标签:私有   return   结构   为什么   amp   返回值   不用   优化   pre   

原文地址:http://www.cnblogs.com/ming-michelle/p/7618015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!