问题描述
我是 C++ 菜鸟,我在理解代码中的 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
& 是什么意思?参数末尾的运算符?
What is the meaning of an & operator at end of parameter?
friend int date_ok( const date& );
谢谢
感谢您的回答.如果我理解正确的话,变量名被简单地省略了,因为它只是一个原型.对于原型,我不需要变量名,它是可选的.对吗?
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?
推荐答案
const date&
被方法 date_ok
接受意味着 date_ok
接受 const date
类型的引用.它的工作原理与指针类似,只是语法稍微有点……含糖
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 = &x
使 Y
成为 int *
类型的指针,然后为其分配地址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
这篇关于变量等末尾的与号 (&)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!