Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

c++ - ampersand (&) at the end of variable etc

I am a C++ noob and i've a problem of understanding c++ syntax in a code. Now I am quite confused.

class date
{
private:
int day, month, year;
int correct_date( void );
public:
void set_date( int d, int m, int y );
void actual( void );
void print( void );
void inc( void );
friend int date_ok( const date& );
};

Regarding to the '&' character, I understand its general usage as a reference, address and logical operator...

for example int *Y = &X

What is the meaning of an & operator at end of parameter?

friend int date_ok( const date& );

Thanks

edit:

Thanks for the answers. If I have understood this correctly, the variable name was simply omitted because it is just a prototype. For the prototype I don't need the variable name, it's optional. Is that correct?

However, for the definition of the function I definitely need the variable name, right?

question from:https://stackoverflow.com/questions/20864574/ampersand-at-the-end-of-variable-etc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

const date& being accepted by the method date_ok means that date_ok takes a reference of type const date. It works similar to pointers, except that the syntax is slightly more .. sugary

in your example, int* Y = &x makes Y a pointer of type int * and then assigns it the address of x. And when I would like to change the value of "whatever it is at the address pointed by Y" I say *Y = 200;

so,

int x = 300;
int *Y = &x;
*Y = 200; // now x = 200
cout << x; // prints 200

Instead now I use a reference

int x = 300;
int& Y = x;
Y = 200; // now x = 200
cout << x; // prints 200

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...