C++引用:
首先,先写一个这样的程序:
#include <iostream>
class point{
private:
int x, y;
public:
point(int x, int y){
this->x = x;
this->y = y;
};
int getX(){
return x;
}
int getY(){
return y;
}
void add(point p){
this->x += p.x;
this->y += p.y;
}
};
int main()
{
point p(1, 1);
p.add(point(2, 2));
std::cout << p.getX() << std::endl;
std::cout << p.getY() << std::endl;
return 0;
}
好,我们现在来分析一下这个程序,我们在执行p.add的方法时,我们又定义了一个这样的point的对象,
来把值给传给它。而在add方法里我们是有定义一个变量的。而将一个值传给另一个变量的话,是默认执行
一个内存拷贝的过程,而这样肯定是要花费时间的。当然,这里的话是不用花费多少时间的,如果你的程序
很庞大的话,你都这样写,就另当别论了,而且这种类型的拷贝是完全没有必要的。而C++也就给我们提供
引用(&)这个功能,当然这个我们也完全可以用指针来做的。。。运用引用符,我们只要少许变动一下就可以了。
#include <iostream>
class point{
private:
int x, y;
public:
point(int x, int y){
this->x = x;
this->y = y;
};
int getX(){
return x;
}
int getY(){
return y;
}
void add(point &p){
this->x += p.x;
this->y += p.y;
}
};
int main()
{
point p(1, 1);
point a(2, 2);
p.add(a);
//p.add(point(2, 2));
std::cout << p.getX() << std::endl;
std::cout << p.getY() << std::endl;
return 0;
}
这样我们也就避免了那个内存拷贝的过程。
PS:加油!