I have some doubts about the syntax for having structs as members of classes.
I have this struct:
/* POS.H */
#ifndef POS_H
#define POS_H
struct pos{
int x;
int y;
pos operator=(const pos& a){
x=a.x; y=a.y;
return a;
}
pos operator+(const pos& a)const {
return (pos){a.x+x,a.y+y};
}
bool operator==(const pos& a)const {
return (a.x==x && a.y== y);
}
};
#endif /* POS_H */
and in another file there is the main function:
/* MAIN.CPP */
#include "pos.h"
#include "clase.h"
int main(){
pos pos;
pos.x=0;
pos.y=0;
clase clase();
}
Then there are 3 different contents for the file clase.h which contains the class clase.
This compiles fine:
#include "pos.h"
class clase{
private:
pos posi;
public:
clase(pos pos):posi(pos){};
};
This does not compile(just changing the name of the member):
#include "pos.h"
class clase{
private:
pos pos;
public:
clase(pos pos):pos(pos){};
This also compiles fine(using pos as neme but using the keyword struct):
#include "pos.h"
class clase{
private:
struct pos pos;
public:
clase(struct pos pos):pos(pos){};
};
My question is: why these codes compile or do not?
It’s traditionally not good coding practice to name a member the same as the struct name, looks like the compiler is getting confused when you try to declare a private member named pos unless you enforce the struct type.
In short it’s just naming conflicts, you should get in the habit of naming members slightly differently than the struct or object name. Perhaps name your structs and objects in TitleCase and then use camelCasing on your members. In this example name the struct POS and then in clase private: POS mPos;