【Rectangle】C++引用问题

今天偶然写两个灰常简单的类,Point,Rectangle,即左上角和右下角标识一个矩形的类。

#include <iostream>
class Point{
public:
Point();
Point(int x);
Point(int x,int y);
int getX();
int getY();
void setX(int new_val);
void setY(int new_val);
void printPoint();
private:
int x;
int y;
};
Point::Point(int x):x(x),y(x){};
Point::Point():x(0),y(0){};
Point::Point(int x,int y):x(x),y(y)
{
};
int Point::getX(){
return x;
}
int Point::getY(){
return y;
}
void Point::setX(int new_val){
x = new_val;
}
void Point::setY(int new_val){
y = new_val;
}
void Point::printPoint(){
std::cout<<"X:"<<x<<",Y:"<<y<<std::endl;
}

int abss(int x,int y){
if(x-y>0){
return x-y;
}else{
return y-x;
}
}


class Rectangle{
public:
Rectangle(Point &lf,Point &rd);
int Calmian();
int Calzhou();
Point &getlu();
private:
Point leftup;
Point rightdown;
};
Point &Rectangle::getlu(){
return leftup;
}
Rectangle::Rectangle(Point &lf,Point &rd):leftup(lf),rightdown(rd){};
int Rectangle::Calmian(){
int x1,x2,y1,y2;
x1 = leftup.getX();
y1 = leftup.getY();
x2 = rightdown.getX();
y2 = rightdown.getY();
return (abss(x1,x2))*(abss(y1,y2));
}
int Rectangle::Calzhou(){
int x1,x2,y1,y2;
x1 = leftup.getX();
y1 = leftup.getY();
x2 = rightdown.getX();
y2 = rightdown.getY();
return 2*(abss(x1,x2)+abss(y1,y2));
}

 

 

 

标红部分一开始没有使用引用,导致test.getlu().setX(9);  该点并未有任何改变,即以by-value的传递方式,getlu()的只是矩形左上点的一个““副本””,并没有真正改变它。

  这个概念上一直记得,写的时候却不记得了,Mark下下。。。

posted @ 2013-12-18 20:04  画家与我  阅读(1709)  评论(0编辑  收藏  举报