在变量结束处的&符号(&)等 [英] ampersand (&) at the end of variable etc
问题描述
我是一个C ++ noob,我有一个问题,在代码中理解c ++语法。现在我很困惑。
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...
例如int * Y =& X
for example int *Y = &X
;
friend int date_ok( const date& );
感谢
edit:
感谢回答者。
如果我正确理解了这一点,变量名只是简单地省略了,因为它只是原型。对于原型我不需要变量名,它是可选的。这是正确的吗?
Thanks for the answesers. If I have understood this correctly, the variable name simply was omitted there because it is just the prototype. And for the prototype i don't need the variable name, it's optional. Is that correct?
但是,对于函数的定义,我需要一定的变量名,对吗?
However, for the definition of the function I need definitely the variable name, right?
推荐答案
const日期&
被方法 date_ok
接受意味着 date_ok
引用 const date
。它的工作类似于指针,除了语法稍微更多.. sugary
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
在你的例子中, int * Y =& code>使
int
类型的指针 Y
。然后为其分配 x
的地址。当我想改变 Y
所指向的地址的值时,我说 * Y = 200;
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;
所以,
int x = 300;
int *Y = &x;
*Y = 200; // now x = 200
cout << x; // prints 200
而现在我使用参考
int x = 300;
int& Y = x;
Y = 200; // now x = 200
cout << x; // prints 200
这篇关于在变量结束处的&符号(&)等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!