codecamp

C++ 作为返回值的结构

你可以写出返回结构的函数。如,findCenter函数把一个Rectangle类型作为参数,返回一个Point类型的值,其中包含着该矩形中心的坐标:

Point findCenter (Rectangle& box)
{
    double x = box.corner.x + box.width/2;
    double y = box.corner.y + box.height/2;
    Point result = {x, y};
    return result;
}

调用这个函数时,我们需要传入一个box作为参数(注意它是通过引用传递的),并把返回值赋给一个Point类型的变量:

Rectangle box = { {0.0, 0.0}, 100, 200};
Point center = findCenter (box);
printPoint (center);

程序输出(50,100)。

C++ 使用结构体表示矩形
C++ 按引用传递其他类型
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定