原题
https://www.codewars.com/kata/return-location
题目
You are given a class named Person with a method named location, which should return the 3D location of the given person.
Can you find the bug?
class Person
{
public:
Person(int x, int y, int z)
: m_x(x), m_y(y), m_z(z)
{
}
void location(int x, int y, int z)
{
x = m_x;
y = m_y;
z = m_z;
}
private:
int m_x;
int m_y;
int m_z;
};
分析
这是一个程序排错问题,考察的参数引用传递。
参考答案
class Person
{
public:
Person(int x, int y, int z)
: m_x(x), m_y(y), m_z(z)
{
}
void location(int& x, int& y, int& z)
{
x = m_x;
y = m_y;
z = m_z;
}
private:
int m_x;
int m_y;
int m_z;
};
说明
值传递和引用传递使用方法相同,但是参数定义方式不同,作用也不同。