J'obtiens l'erreur suivante lorsque j'essaie de passer un Point
objet par référence en gardant Point
les variables membres x et y comme privées, c'est pourquoi j'obtiens x et y par fonction GetX()
et GetY()
comment puis-je résoudre l'erreur et la faire fonctionner comme je l'attends pour.
journal des erreurs :
CppReview.cpp: In function 'int main()':
CppReview.cpp:92:30: error: cannot bind non-const lvalue reference of type 'Point&' to an rvalue of type 'Point'
92 | v.OffSetVector(v.GetStart(),1,3);
| ~~~~~~~~~~^~
CppReview.cpp:79:34: note: initializing argument 1 of 'void Vector::OffSetVector(Point&, int, int)'
79 | void Vector::OffSetVector(Point& p,int xoffset,int yoffset){
code :
class Point{
private:
int x,y;
public:
Point(){
x = y = 0;
}
Point(int x,int y){
this->x = x;
this->y = y;
}
Point(float x,float y){
this->x = x;
this->y = y;
}
void SetX(int x){
this->x = x;
}
void SetY(int y){
this->y = y;
}
void Display(){
cout<<"("<<this->x<<','<<this->y<<")\n";
}
void move(int i=0,int j=0){
this->x+=i;
this->y+=j;
}
int& GetX(){
return (this->x);
}
int& GetY(){
return this->y;
}
};
class Vector{
Point start,end;
public:
Vector(){
this->start = Point(0,0);
this->end = Point(1,1);
}
Vector(int sx,int sy,int ex,int ey){
this->start = Point(sx,sy);
this->end = Point(ex,ey);
}
float ComputeDistance(Point,Point);
Point GetStart();
Point GetEnd();
void OffSetVector(Point&,int,int);
void Show();
};
float Vector::ComputeDistance(Point p1,Point p2){
int p1x = p1.GetX();
int p1y = p1.GetY();
int p2x = p2.GetX();
int p2y = p2.GetY();
float dist = sqrt((p1x-p2x)*(p1x-p2x)+(p1y-p2y)*(p1y-p2y));
return dist;
}
Point Vector::GetStart(){
return this->start;
}
Point Vector::GetEnd(){
return this->end;
}
void Vector::OffSetVector(Point& p,int xoffset,int yoffset){
p.GetX()+=xoffset;
p.GetY()+=yoffset;
}
void Vector::Show(){
cout<<this->GetStart().GetX()<<','<<this->GetStart().GetY()<<" : "<<this->GetEnd().GetX()<<','<<this->GetEnd().GetY()<<"\n";
}
int main(){
Vector v(1,1,3,3);
v.Show();
v.OffSetVector(v.GetStart(),1,3);
return 0;
}
La fonction GetStart renvoie un objet temporaire de type Point
Point GetStart();
tandis que la fonction OffsetVector excepte une référence non constante à un objet.
void OffSetVector(Point&,int,int);
Vous ne pouvez pas lier un objet temporaire avec une référence lvalue non cinstant.
Modifiez la déclaration de la fonction GetStart comme
Point & GetStart();
Aussi au moins la fonction GetEnd doit être modifiée comme
Point & GetEnd();
Vous pourriez surcharger les fonctions pour les objets constants et non constants
Point & GetSgtart();
cosnt Point & GetStart() const;
Point & GetEnd();
const Point & GetEnd() const;
Cet article est collecté sur Internet, veuillez indiquer la source lors de la réimpression.
En cas d'infraction, veuillez [email protected] Supprimer.
laisse moi dire quelques mots